Jump to content

php regex accepts pattern although should discard


gintare

Recommended Posts

 $pattern="/[+][0-9]+[^a-zA-Z*-+!|@#$%&*(){\/}]/"; //
 $subject="+3706*0805595";
 $ans=preg_match($pattern, $subject, $matches);
 print_r($matches);echo "ans=".$ans;

gives output

Array ( [0] => +3706 ) ans=1

Where is my mistake. How to formulate pattern which does not accept string which contains letters or special characters.

String must start with +, contain digits.

Apply anchors to your regex (^ and $). Also there is no need to also specify the characters you dont want to match. You only need to specify the characters you want to match

$pattern="/^\+[\d]+$/";

$subject="+370608*05595"; // does not match, however removing the * will match

$ans=preg_match($pattern, $subject, $matches);
print_r($matches);
$pattern="/^\+[\d]+$/";

$subject="+370608*05595"; // does not match, however removing the * will match

$ans=preg_match($pattern, $subject, $matches);
print_r($matches);

 

Not quite.

  • Use \A and \z instead of ^ and $. The former are unambigious, whereas the latter have different meanings depending on the modifiers.
  • Always escape backslashes, especially if you're using double-quoted strings. A blackslash within a PHP string actually has a meaning, and that can result in unexpected characters or syntax errors. If you want a backslash in a regex, that's a double backslash in the regex strings.
  • Don't use double-quoted strings for regexes. They have special parsing rules which again can turn your regex string into something unexpected.
  • No need to put \d into a character class. It's a character class by itself.

 

 

So a proper regex string would look something like this:

$my_regex = '/\\A\\+\\d+\\z/';

When you're dealing with more complex regexes which would require an excessive amount of backslashes, use nowdocs instead:

$my_regex = <<<'REGEX'
/\A\+\d+\z/
REGEX;

Then and only then you can use simple backslashes.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.