Home > Software engineering >  How to write regular expression to Validate phone number of format (0d)dddddddd in php using preg_ma
How to write regular expression to Validate phone number of format (0d)dddddddd in php using preg_ma

Time:10-23

I have been trying but not sure where i am wrong

$validator = preg_match('/^\(\0\d{1})?\d{8})$/', $phone);

if($validator == true)
{
    echo "Valid phonenumber";
}
else
{
    echo "Invalid phonenumber";
}

CodePudding user response:

There are several issues in `^(\0\d{1})?\d{8})$:

  • \0 matches the NUL (\x00) char
  • )? here is trying to close an optional group, but there is no matching ( before that position
  • The ) at the $ anchor is also trying to close a group, but there is no matching ( anywhere before.

I suggest just using

$validator = preg_match('/^\(0\d\)\d{8}$/', $phone);

See the regex demo. If the (0d) part is optional and can be missing, wrap that part with an optional non-capturing group, e.g.

$validator = preg_match('/^(?:\(0\d\))?\d{8}$/', $phone);

See this regex demo.

  • Related