开发者

preg_match how to negate preceding zeros in a phone number?

I'm just learning regular expressions so I could use some help on this topic regarding the validation of phone numbers.

I have a phone input that is divided into one select list with country codes prefixed with a + sign. If a user forgets to remove the preceding zero in the phone number it won't be in accordance to the E.164 international standard (There are however a handful of countries that are an exception to this rule, i.e. Italy, Norway etc). But the majority needs to omit the zero for a valid international phone number.

In my albeit limited research, I've realized that phone number formats vary significantly across the world. This means the validation needs to be loose rather th开发者_StackOverflow社区an strict and allow for any combination of dashes, spaces, parenthesis, dots and forward slashes as delimiters between numbers. To fit the E.164 standard the delimiters will then be replaced by empty strings to give an example result like this: +44755222333

This is my attempt thus far for validating any number.

preg_match('/^(?:[0-9][.\-\(\)\s]*)/$', $phonenumber);

How would you compose a regular expression to negate preceding zeros i.e return a false match in presence of the string character 0 or 00, coupled with the flexibility to validate any possible telephone number notation?

Sincerely, Why

P.S Just to check. Does the 'no zero' rule apply for NANP numbers as well? I'm asking this because I assume the majority of the people here are familiar with that telephone numbering system.


You can use preg_replace to strip off the leading zeros:

$phonenumber = preg_replace('/^0+/','',$phonenumber);

This will remove one or more zeros from the front of the string. (If you only want to remove one zero, then drop the plus sign).

Hope that helps.


How about this:

$number = '044567565';
preg_match('/^0{0,2}(([0-9]*[.\-\(\)\s]*)*)/', $number, $match);
print_r($match);

Result:

array(
    [0] => 044567565
    [1] => 44567565
    [2] => 
)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜