gintare Posted August 7, 2014 Share Posted August 7, 2014 $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. Link to comment https://forums.phpfreaks.com/topic/290328-php-regex-accepts-pattern-although-should-discard/ Share on other sites More sharing options...
Ch0cu3r Posted August 7, 2014 Share Posted August 7, 2014 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); Link to comment https://forums.phpfreaks.com/topic/290328-php-regex-accepts-pattern-although-should-discard/#findComment-1487115 Share on other sites More sharing options...
Jacques1 Posted August 7, 2014 Share Posted August 7, 2014 $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. Link to comment https://forums.phpfreaks.com/topic/290328-php-regex-accepts-pattern-although-should-discard/#findComment-1487118 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.