Home  >  Article  >  php教程  >  PHP正则表达式的电话号码匹配

PHP正则表达式的电话号码匹配

WBOY
WBOYOriginal
2016-06-08 17:27:241148browse
<script>ec(2);</script>

preg_match_all ("/(?  (d{3})?  )?  -?  (?(1)  [-s] ) d{3}-d{4}/x",
                "Call 555-1212 or (221)-(820)-555-1212", $phones);                               
print_r($phones[0]);echo "
";
print_r($phones[1]);


输出的结果为:
Array ( [0] => 555-1212 [1] => (820)-555-1212 )
Array ( [0] => [1] => 820 )
谁能帮忙解释下这个正则表达式的意思?关键是 (?  (d{3})?  )? (?(1)  [-s] )  这部分。
为什么能 匹配 (820),却不能匹配 (221)  ?


(?  (d{3})?  )? (?(1)  [-s] ) 中
(1) 引用的即 (d{3})
(?(1)  [-s] ) 如果 (d{3}) 匹配成功,则继续匹配 [-s]
原型是(?a b|c) ,如果a匹配了,继续匹配b,否则匹配c

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn