帮助使用 preg_match 获取电话号码
我将如何编写一个 if 语句来查找电话号码并将其存储到变量中。这是我到目前为止所拥有的,但它不起作用。
if (preg_match('/^(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$
/', $buffer, $matches))
{
$phonenumber = html_entity_decode($matches[1]);
}
how would i write an if statement that would find phone numbers and store them to a variable. Here is what i have so far but its not working.
if (preg_match('/^(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$
/', $buffer, $matches))
{
$phonenumber = html_entity_decode($matches[1]);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于您使用的是
preg_match()
,我假设您使用的是 PHP。对于电话号码,因为即使在北美,电话号码也存在差异。 (11,10 或 7 位数字,变化或没有分隔字符等)您可能会发现这样的函数比正则表达式更容易处理:ETA 您在评论中的问题:
的字符串
您有一个应该是电话号码
validphone()
函数最适合应为电话号码的短字符串。如果将整个页面转储到字符串中,然后将其提供给validphone($mywholepage)
,它将立即提取字符串中的所有数字。因此,包含多个电话号码的文本将返回 false,而恰好分布有 11,10 或 7 位数字的文本将返回 true。Since you're using
preg_match()
, I'll assume you're using PHP. For phone numbers, because of their variability even in N.Am. (11,10 or 7 digits, varying or no separating characters, etc.) you may find a function like this easier to deal with than a regex:ETA your questions in the comments:
You have a string that should be a phone number
The
validphone()
function is most appropriate for shortish strings that are expected to be phone numbers. If you dump an entire page into a string and then feed it tovalidphone($mywholepage)
, it will extract all the numbers in the string at once. So text with multiple phone numbers will return false and text that happens to have 11,10 or 7 digits distributed throughout will return true.一开始,您搜索可选的
+1
和一些贪婪的字符串。更改为
应该可以解决问题,但也许您的正则表达式中存在更多问题。
In the beginning, your searching for optional
+1
and some greedy string. Changingto
should do the trick, but maybe there are even more problems in your regex.