我正在尝试编写一个小脚本来查明给定字符串是否包含电话号码和/或电子邮件地址。
这是我到目前为止所拥有的:
function findContactInfo($str) {
// Find possible email
$pattern = '/[a-z0-9_\-\+]+@[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
我遇到的问题是我不知道如何找到这样的组合。即使在网上搜索了近一个小时后,我也找不到解决方案。 有人对如何解决这个问题有建议吗? 谢谢!
最佳答案
你可以使用
\b\d[- /\d]*\d\b
长版:
\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);
?>
这样做的问题是,您可能会得到很多误报,因此当这些匹配被清理、规范化然后针对数据库进行测试时,肯定会提高您的准确性。
至于您的电子邮件问题,我经常使用:
\S+@\S+
# not a whitespace, at least once
# @
# same as above
有几十个不同的有效电子邮件,证明其中是否有真人的唯一方法是发送一封带有链接的电子邮件(即使这可以自动化)。
关于PHP - 在字符串中搜索电话号码和电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43856018/