我正在尝试在纯文本之间获取电话号码。但在这里,我面临着一些典型的问题。我写的模式与所有类型的电话号码都不匹配。
Ex:
$string = 'sample text sample text sample text (216) 499 1001 sample text sample text (262) 335 60 76-77 sample text sample text sample text';
$string = str_replace('\n', PHP_EOL, $string);
//my regex pattern
$regex = '/(?:1(?:[. -])?)?(?:\((?=\d{3}\)))?([2-9]\d{2})(?:(?<=\(\d{3})\))? ?(?:(?<=\d{3})[.-])?([2-9]\d{2})[. -]?(\d{4})(?: (?i:ext)\.? ?(\d{1,5}))?\s+?/';
preg_match_all($regex, $string, $matches);
print_r($matches);
这是给我第一个电话号码,但不是第二个。 Plz也帮助我获得了这种模式。
Output:
Array
(
[0] => Array
(
[0] => (216) 499 1001
)
----
---
提前致谢!
答案 0 :(得分:1)
您好我会为此编写算法
1)将整个字符串提取到数组中 2)使用for循环开始扫描文档(直到行结束) 3)使用is_numeric函数查找查找号码并计算总数,然后使用if语句(10位=电话号码,5位数=这样的邮政编码) 4)如果是电话号码,则将值移入临时数组,否则下一行(使用空格作为分隔符) 4)现在你可以处理所有
如果您想使用区号或服务提供商过滤电话号码,您可以使用以下代码
<?php
$strings = array('+91', '+11', '+97');
foreach ($strings as $testcase) {
if (ctype_digit($testcase)) {
echo "Match found .\n";
} else {
echo "Not matching.\n";
}
}
?>