Author Topic: PHP Reg Expression and $  (Read 1818 times)

Mike

  • Jackass In Charge
  • Posts: 11248
  • Karma: +168/-32
  • Ex Asshole - a better and more caring person.
PHP Reg Expression and $
« on: August 22, 2008, 12:52:36 AM »
Recently found out that the default behavior of $ in a regular expression will match a newline before the end of string.
So:
Code: [Select]
<?php

$tests 
= array(
"123456",
"123456\n",
);

foreach(
$tests AS $test)
{
$good preg_match('~^[0-9]+$~'$test);

echo '"'$test'" '$good 'is' 'is not'' good<br />';
}

?>
Gives
Code: [Select]
"123456" is good
"123456 " is good

To "correct" this you can use the D modifier so that $ really means the end of the string.
Code: [Select]
<?php

$tests 
= array(
"123456",
"123456\n",
);

foreach(
$tests AS $test)
{
$good preg_match('~^[0-9]+$~D'$test);

echo '"'$test'" '$good 'is' 'is not'' good<br />';
}

?>
Gives:
Code: [Select]
"123456" is good
"123456 " is not good

This matters if you use a regular expression as a form of verification but don't change the value if it passes the expression.

I do have a hard time thinking of what a newline could break but I'm sure its possible.  If nothing else on at the end of an email address could break the send mail.