2017-05-08 106 views
1

我想写一个小脚本来找出给定的字符串是否包含电话号码和/或电子邮件地址。PHP - 搜索字符串的电话号码和电子邮件

这里是我到目前为止有:

function findContactInfo($str) { 
    // Find possible email 
    $pattern = '/[a-z0-9_\-\+][email protected][a-z0-9\-]+\.[a-z]{2,3}?/i'; 
    $emailresult = preg_match($pattern, $privateMessageText); 

    // Find possible phone number 
    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]; 
} 

的部分与邮件工作正常,但我愿意接受改进。 随着电话号码我有一些问题。首先,将被赋予该函数的字符串很可能包含德语电话号码。这个问题是所有不同的格式。它可能类似于 030 - 1234567或030/1234567或02964-723689或01718290918 等。所以基本上我几乎不可能找出什么样的组合会被使用。所以我在想的是,也许最好是找到至少三位数字的组合。例如:

$stringOne = "My name is John and my phone number is 040-3627781"; 
// would be found 

$stringTwo "My name is Becky and my phone number is 0 4 0 3 2 0 5 4 3"; 
// would not be found 

我遇到的问题是我不知道如何找到这样的组合。即使经过近一个小时的网络搜索,我找不到解决方案。 有没有人有如何解决这个问题的建议? 谢谢!

+0

怎么样:'/ \ b [\ d - \ /] {4,} \ b /'?演示在这里: https://regex101.com/r/lbemPI/1 – degant

+0

它给了我这个错误: 警告:preg_match()期望参数2是字符串,在 – Dennis

+0

给出的数组中给出的数字格式为“ 3-3-4'作为一种官方或商业形式,但人们往往会分享他们的号码,而非法国人,比如'3-2-2-2-2-2'。来源:*德国朋友。* – Martin

回答

2

你可以使用

\b\d[- /\d]*\d\b 

a demo on regex101.com


龙版本:

\b\d  # this requires a "word boundary" and a digit 
[- /\d]* # one of the characters in the class 
\d\b  # a digit and another boundary. 


PHP

<?php 
$regex = '~\b\d[- /\d]*\d\b~'; 

preg_match_all($regex, $your_string_here, $numbers); 
print_r($numbers); 
?> 

问题与此是,你可能会得到大量的误报,所以它肯定会提高你的准确度时,这些比赛清理,标准化,然后针对数据库进行测试。


至于你 的问题通过电子邮件,我经常使用:

\[email protected]\S+ 
# not a whitespace, at least once 
# @ 
# same as above 

有几十个不同的有效电子邮件,以证明的唯一办法,如果有一个实际的人后面一个是从一个发送电子邮件链接(即使这可能是自动的)。

+0

完美!非常感谢。 – Dennis

+0

@丹尼斯:不客气,很乐意帮忙。 – Jan

相关问题