本文介绍了查找字符串中的电话号码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PHP中,我正在搜索特定文本中的电话号码.我使用explode()将文本分为不同部分,使用我要搜索的城市的区号作为分隔符.问题在于,包含相同号码作为区号的电话号码不能很好地返回.

In PHP I'm searching for phonenumbers in a certain text.I use explode() to divide the text in different parts,using the area code of the city I'm searching for as the delimiter. The problem is that phonenumbers that include the same numbers as the area-code are not returned well.

例如:

"foofoo 010-1234567 barbar"分为"foofoo ""-1234567 barbar"

但是

"foofoo 010-1230107 barbar"分为"foofoo ""-123""7 barbar"

我可以使用第一个用区号重建电话号码,但是第二个当然不对...

I can use the first one to reconstruct the phonenummer with the areacode, but the second goes wrong of course...

我想我需要一个正则表达式来使用某种机制将文本拆分为 not 而不是explode()而不是短字符串,但是我不知道该怎么做.

I guess I need a regular expression to split the text with some kind of mechanism to not split on short strings, instead of explode() , but I don't know how to do it.

有什么想法或更好的方法来搜索文本中的电话号码吗?

Any ideas or a better way to search for phonenumbers in a text ?

更新: 格式不一致,因此寻找连字符不是解决方案.有些电话号码的区号和号码之间有空格,有些电话带钩,有些没有,等等.荷兰电话号码的区号为2、3或4,通常总共为10.

UPDATE:The format is NOT consistent, so looking for the hyphen is no solution. Some phone numbers have spaces between the area code and number, some have hooks, some have nothing, etc. Dutch phonenumbers have an areacode of 2,3 or 4 numbers and are usually 10 numbers in total.

推荐答案

要查找以下电话号码:

  • 010-1234010
  • 010 1234010
  • 010 123 4010
  • 0101234010
  • 010-010-0100

尝试一下:

$text = 'foofoo 010-1234010 barbar 010 1234010 foofoo ';
$text .= ' 010 123 4010 barbar 0101234010 foofoo 010-010-0100';

$matches = array();

// returns all results in array $matches
preg_match_all('/[0-9]{3}[\-][0-9]{6}|[0-9]{3}[\s][0-9]{6}|[0-9]{3}[\s][0-9]{3}[\s][0-9]{4}|[0-9]{9}|[0-9]{3}[\-][0-9]{3}[\-][0-9]{4}/', $text, $matches);
$matches = $matches[0];

var_dump($matches);

这篇关于查找字符串中的电话号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 03:26