繁体   English   中英

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

[英]PHP regex for specific phone number format

我试图验证电话号码在PHP中。 要求为(0d)dddddddd或0d dddddddd,其中d为0-9。 这就是我现在所拥有的

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

我已经尝试了几个类似的问题,但仍然不能很好地理解正则表达式。 谁能帮我修复正则表达式?

您可以尝试以下代码,

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

DEMO

说明:

^                        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}$

试试看。看演示。

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

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

火柴

(05)12345678
05 12345678

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

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

尝试这个

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