简体   繁体   English

适用于特定电话号码格式的PHP正则表达式

[英]PHP regex for specific phone number format

im trying to validate phone number in php. 我试图验证电话号码在PHP中。 The requirements are (0d)dddddddd or 0d dddddddd where d is 0-9. 要求为(0d)dddddddd或0d dddddddd,其中d为0-9。 This is what I have right now 这就是我现在所拥有的

if(!preg_match("/^0[0-9]{9}$/", $phone))
{
//wrong format
}

I have tried several similar questions, but still cant understand regex very well. 我已经尝试了几个类似的问题,但仍然不能很好地理解正则表达式。 Can anyone help me fix the regex? 谁能帮我修复正则表达式?

You could try the below code, 您可以尝试以下代码,

if(!preg_match("~^(?:0\d\s|\(0\d\))\d{8}$~", $phone))
{
//wrong format
}

DEMO DEMO

Explanation: 说明:

^                        the beginning of the string
(?:                      group, but do not capture:
  0                        '0'
  \d                       digits (0-9)
  \s                       whitespace 
 |                        OR
  \(                       '('
  0                        '0'
  \d                       digits (0-9)
  \)                       ')'
)                        end of grouping
\d{8}                    digits (0-9) (8 times)
$                        before an optional \n, and the end of the
                         string
^(?:\(0\d\)|0\d\s)\d{8}$

Try this.See demo. 试试看。看演示。

http://regex101.com/r/wQ1oW3/8 http://regex101.com/r/wQ1oW3/8

^((\(0\d\))|(0\d ))\d{8}$

matches 火柴

(05)12345678
05 12345678

see the example http://regex101.com/r/zN4jE4/1 参见示例http://regex101.com/r/zN4jE4/1

if(!preg_match("/^((\(0\d\))|(0\d ))\d{8}$/", $phone))
{
//wrong format
}

try this 尝试这个

if(!preg_match("^(?:\(0\d\)|0\d\s)\d{8}$", $phone))
{
//wrong format
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM