Why does this regular expression result in: “preg_

2019-09-11 16:19发布

问题:

This question already has an answer here:

  • PHP regular expressions: No ending delimiter '^' found in 3 answers

I am writing a regular expression to extract a pattern of numbers from a string. When I used to run the below code snippet, it is showing a warning

"preg_match() [<a href='function.preg-match'>function.preg-match</a>]: No ending delimiter '^' "

Could any one tell me why this warning and how to fix it?

$temp=0;
$exp=(explode(" ",$message1));
while($temp<sizeof($exp))
{
    if(preg_match("^(+91|0091|0)?[7-9][0-9]{9}$",$exp[$temp]))
    {
    $pat=$exp[$temp];

    }
}

回答1:

You forgot the regex delimiter, use this instead (inserted / at the very beginning and end of the regex):

if(preg_match('/^(+91|0091|0)?[7-9][0-9]{9}$/', $exp[$temp]))

The reason for the error you got is that PHP allows any delimiter character. In your case it used ^ since that's the first character in your string. However, that obviously didn't work since it never found another caret to end the regex. Using ^ would be a bad idea anyway since it has a meaning in the regex itself.



标签: php regex wamp