php preg_replace电话号码

Jac*_*anz 2 php regex

我想用html字符串替换给定的电话号码,例如

<a>click here now! (123) -456-789</a>
Run Code Online (Sandbox Code Playgroud)

我认为接近它的最佳方法是找到看起来像电话号码的所有不同情况,例如:

$pattern = *any 3 numbers* *any characters up to 3 characters long* 
$pattern .= *any 3 numbers* *any characters up to 3 characters long* 
$pattern .= *any numbers up to 4 numbers long*

// $pattern maybe something like [0-9]{3}\.?([0-9]{3})\.?([0-9]{4})

$array = preg_match_all($pattern, $string);

foreach($array)
{
    // replace the string with the the new phone number
}
Run Code Online (Sandbox Code Playgroud)

基本上,正则表达式将如何?

Abs*_*ERØ 9

根据维基百科中写入电话号码本地惯例,如果您要删除所有电话号码,全球有多种格式.在以下示例中,占位符0代表一个数字.以下是wiki条目中的示例(可能有重复项).

0 (000) 000-0000
0000 0000
00 00 00 00
00 000 000
00000000
00 00 00 00 00
+00 0 00 00 00 00
00000 000000
+00 0000 000000
(00000) 000000
+00 0000 000000
+00 (0000) 000000
00000-000000
00000/000000
000 0000
000-000-000
0 0000 00-00-00
(0 0000) 00-00-00
0 000 000-00-00
0 (000) 000-00-00
000 000 000
000 00 00 00
000 000 000
000 000 00 00
+00 00 000 00 00
0000 000 000
(000) 0000 0000
(00000) 00000
(0000) 000 0000
0000 000 0000
0000-000 0000
0000 000 0000
00000 000000
0000 000000
0000 000 00 00
+00 000 000 00 00
(000) 0000000
+00 00 00000000
000 000 000
+00-00000-00000
(0000) 0000 0000
+00 000 0000 0000
(0000) 0000 0000
+00 (00) 000 0000
+00 (0) 000 0000
+00 (000) 000 0000
(00000) 00-0000
(000) 000-000-0000
(000) [00]0-000-0000
(00000) 0000-0000
+ 000 0000 000000
8.8.8.8
192.168.1.1
0 (000) 000-0000 ext 1
0 (000) 000-0000 x 1001
0 (000) 000-0000 extension 2
0 000 000-0000 code 3
Run Code Online (Sandbox Code Playgroud)

因为虽然你可以尝试写一些疯狂的REGEX,根据它的国家代码,拨打前缀等来符合你的目的,但这不是必需的,这将是浪费时间.从贝叶斯方法来看,较长的数字往往是18个字符(阿根廷移动数字),可能有一个前导+字符后跟数字[0-9]\d括号(),括号[]和可能的空格, periods .或连字符-以及一个带有a的模糊格式/.

\b\+?[0-9()\[\]./ -]{7,17}\b
Run Code Online (Sandbox Code Playgroud)

对于所有这些数字,我们还会附加以下扩展格式

ext 123456
x 123456
# 123456
EXT 123456
- 123456
code 2
-12
Extension 123456

\b\+?[0-9()\[\]./ -]{7,17}\s+(extension|x|#|-|code|ext)\s+[0-9]{1,6}
Run Code Online (Sandbox Code Playgroud)

总的来说,你会寻找带有扩展名的电话号码或电话号码:

$pattern = '!(\b\+?[0-9()\[\]./ -]{7,17}\b|\b\+?[0-9()\[\]./ -]{7,17}\s+(extension|x|#|-|code|ext)\s+[0-9]{1,6})!i';
Run Code Online (Sandbox Code Playgroud)

注意:这也会剥离IP地址.如果要保留IP地址,则需要将IP地址中的句点替换为与我们的电话号码正则表达不匹配的句点,然后将其切换回来.

因此,对于您的代码,您将使用:

$string = preg_replace($pattern,'*Phone*',$string);
Run Code Online (Sandbox Code Playgroud)

这是匹配测试PHP小提琴.