我很难找到一个可以检测到以下内容的模式
909-999-9999
909 999 9999
(909) 999-9999
(909) 9999999
999 999 9999
9999999999
\A[(]?[0-9]{3}[)]?[ ,-][0-9]{3}[ ,-][0-9]{3}\z我试过了,但它并不适用于所有的实例。我在想,我可以通过将每个字符放入一个数组中,然后检查它来划分问题。但是这样代码就太长了。
发布于 2015-10-16 05:28:58
最后一组中有4个数字,在正则表达式中指定为3。
您还需要对分隔符应用?量词(1次或0次),因为它们是可选的。
使用
^[(]?[0-9]{3}[)]?[ ,-]?[0-9]{3}[ ,-]?[0-9]{4}$PHP demo
$re = "/\A[(]?[0-9]{3}[)]?[ ,-]?[0-9]{3}[ ,-]?[0-9]{4}\z/";
$strs = array("909-999-9999", "909 999 9999", "(909) 999-9999", "(909) 999 9999", "999 999 9999","9999999999");
$vals = preg_grep($re, $strs);
print_r($vals);和another one
$re = "/\A[(]?[0-9]{3}[)]?[ ,-]?[0-9]{3}[ ,-]?[0-9]{4}\z/";
$str = "909-999-9999";
if (preg_match($re, $str, $m)) {
echo "MATCHED!";
}顺便说一句,可选的?子模式比交替执行得更好。
发布于 2015-10-16 05:25:15
试试这个正则表达式:
^(?:\(\d{3}\)|\d{3})[- ]?\d{3}[- ]?\d{4}$解释:
^ # from start
(?: # one of
\(\d{3}\) # '(999)' sequence
| # OR
\d{3} # '999' sequence
) #
[- ]? # may exist space or hyphen
\d{3} # three digits
[- ]? # may exist space or hyphen
\d{4} # four digits
$ # end of string希望能有所帮助。
https://stackoverflow.com/questions/33158774
复制相似问题