2014-10-19 91 views
0

即时通讯尝试在php中验证电话号码。要求是(0d)dddddddd或0d dddddddd,其中d是0-9。这是我现在所拥有的特定电话号码格式的PHP正则表达式

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

我试过几个类似的问题,但仍不能理解正则表达式。 任何人都可以帮我修复正则表达式吗?

+0

你能否提供一些有效数字的例子 – nu11p01n73R 2014-10-19 07:34:29

+0

当然可以。像(05)12345678或05 12345678 – bisonsausage 2014-10-19 07:41:42

+1

“类似的东西”在讨论正则表达式时不够好。你必须尽可能精确。 – 2014-10-19 07:54:04

回答

1

你可以试试下面的代码,

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

感谢您的解释,真正帮助那些仍然像我一样学习的人。欣赏它。 – bisonsausage 2014-10-19 08:04:08

0

试试这个

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