Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

regex question, hopefully easy

Status
Not open for further replies.

jez

Programmer
Apr 24, 2001
370
VN
Hi Everyone,

I am having an issue with a preg_match.
It seems to be finding false positives, this is almost certainly down to a mistake on my part in the pattern, can someone cast their eyes over it and give me tips

Code:
	$compareStr = basename($_SERVER['PHP_SELF']);
	$pattern = "/[login.php|forgottenPassword.php]/i";
	$pos = preg_match($pattern, $compareStr);

I am trying to cause different behaviour in a file included everywhere on the site except in the two pages mentioned.

The next line of the code is
Code:
if($pos < 1){
	header("Location: ". BASE_URL);
	}

Now when i access a pages called
areaList.php?chapterid=3
and echo the value of $pos, it says 1, which would indicate a match on the preg_match, wouldn't it?

Thank in advance,

Jez
 
escape the dot in the filenames. dot has a special meaning in regex.

although i have to say that i'm not convinced a preg_match is a good thing to use for such a simple comparison.

why not
Code:
$array = array("login.php","forgottenpassword.php");
if (in_array( basename($_SERVER['PHP_SELF']), $array)) {
  // do something
}

 
Thanks, you may be right about it being too much for such a simple action but i wanted to make it scalable (within reason) and the suggestion about arrays is the way to do that.

Also regarding the dot, i thought that i would be ok with that as it is within quotes.

I have managed to make it work now, with

Code:
$pattern = '/(login.php|forgottenPassword.php)/i';

In my first attempt the square brackets were making a class to compare to, so anything that had any of the charaters in the file names would cause a positive match.

Thanks for the input, i think i will change it to arrays now.

Jez
 
i still think the regex is wrong.

i'd think something like
Code:
$pattern = '/[login\.php] | [forgottenPassword\.php]/i';
is more likely to be accurate.
 
But doesn't the square brackets mean that it will match 'l', 'o','g' etc etc? And since it is working at the moment, i think that the dot which matches any charater is matching a the literal dot.
Having said that for correctness i should escape the dot.

Thanks

Jez
 
you are right on the brackets.

but you do need to escape the dot otherwise it will be interpreted by regex as the "any character" metacharacter, thus matching both loginphp and login.php (as well as loginZphp etc).
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top