我需要帮助编写与某些数据中的电话号码相匹配的常规表达。 Somin采用以下格式:
XXX-XXX-XXXX
XXX-XXX-XXXX Ext. XXX
XXX-XXX-XXXX Ext. XXXX
(XXX) XXX-XXXX
XXX-XXX-XXXX (Text)
XXX.XXX.XXXX
和一行专门用于此行:
XXX-XXX-XXXX (Text & Special Chars.); XXX-XXX-XXXX (Text)
我已经搜索了几个问题并尝试了一般的0-9比赛但到目前为止无济于事。我最近也试过这个来获取正常的电话号码:
preg_match_all('/^((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}$/', $a3, $n);
print_r($n);
有人能告诉我正确的方法吗?感谢
答案 0 :(得分:2)
此模式将与您在任何文本中提供的示例相匹配。
((?:\d{3}[.-]|\(\d{3}\)\s+)\d{3}[.-]\d{4})(?:\s+Ext\.\s+(\d+)|\s+\(.*?\))?
如果您可以提供一些样本数据或更详细地解释主题的样子,那么该模式可能会得到改善。例如,所有数字是否在单独的行上(如您的模式所示)或者它们是文本的一部分吗?
示例脚本和解释的模式:
$string = <<<EOT
123-456-7890
123-456-7890 Ext. 321
123-456-7890 Ext. 4321
(123) 456-7890
lorem ipsum
123-456-7890 (Text)
123.456.7890
foo bar baz
EOT;
//preg_match_all("/((?:\d{3}[.-]|\(\d{3}\)\s+)\d{3}[.-]\d{4})(?:\s+Ext\.\s+(\d+)|\s+\(.*?\))?/i", $string, $matches);
preg_match_all("/
( # open capturing group to hold the phone number
(?: # open non-capturing group
\d{3}[.-] # match 3 digits followed by a . or -
| # OR, if the previous part of this group did not match
\(\d{3}\)\s+ # match 3 digits between parentheses folowed by one or more spaces
) # close non-capturing group
\d{3}[.-] # match 3 digits followed by a . or -
\d{4} # match 4 digits
) # close capturing group
(?: # open non-capturing group
\s+Ext\.\s+ # one or more spaces followed by Ext. followed by one or more spaces
( # open capturing group to hold the extension number
\d+ # match one or more digits
) # close capturing group
| # OR, if the previous part of this non-capturing group did not match
\s+\(.*?\) # one or more spaces and then anything, except newline, between (the smallest) pair of parentheses
)? # close non-capturing group, the ? makes the whole non-capturing group optional
/ix", $string, $matches);# the i flag makes the matches case insensitive and x allows for the comments and spacing
echo "<pre>\n";
print_r($matches);
输出:
Array
(
[0] => Array
(
[0] => 123-456-7890
[1] => 123-456-7890 Ext. 321
[2] => 123-456-7890 Ext. 4321
[3] => (123) 456-7890
[4] => 123-456-7890 (Text)
[5] => 123.456.7890
)
[1] => Array
(
[0] => 123-456-7890
[1] => 123-456-7890
[2] => 123-456-7890
[3] => (123) 456-7890
[4] => 123-456-7890
[5] => 123.456.7890
)
[2] => Array
(
[0] =>
[1] => 321
[2] => 4321
[3] =>
[4] =>
[5] =>
)
)
而对于另一行,上面的模式也会匹配那个,但如果你确实需要它,那么
$string = "123-456-7890 (Text & Special Chars.); 123-456-7890 (Text)";
preg_match_all("/(\d{3}[.-]\d{3}[.-]\d{4})\s+\(.*\);\s+(\d{3}[.-]\d{3}[.-]\d{4})\s+\(.*?\)/i", $string, $matches);
echo "<pre>\n";
print_r($matches);
输出:
Array
(
[0] => Array
(
[0] => 123-456-7890 (Text & Special Chars.); 123-456-7890 (Text)
)
[1] => Array
(
[0] => 123-456-7890
)
[2] => Array
(
[0] => 123-456-7890
)
)