简体   繁体   English

用于检测PHP中错误电话号码的正则表达式

[英]Regular expression to detect faulty phone numbers in PHP

I am trying to build a regular expression to detect faulty phone numbers and replace them with the original one. 我正在尝试构建一个正则表达式以检测错误的电话号码并将其替换为原始电话号码。 I have the phone number and in a text field with text (with html tags) are the faulty numbers (users of the site like to put various characters in between the number for some reason). 我有电话号码,并且在带有文本(带有html标签)的文本字段中是错误的号码(出于某种原因,该网站的用户喜欢在号码之间放置各种字符)。 Here is what I am using which works fine on most cases but not all: 这是我正在使用的方法,在大多数情况下都可以正常使用,但并非全部:

$phone = '0888123123';
$text = 'Some html text with variants of the phone number in wrong format - 
0~8~8~8~1~2~3~1~2~3
0.8.8.8.1.2.3.1.2.3
0 8 8 8 1 2 3 1 2 3
0888-123-123
The last format does not work!';

preg_match_all('/('.implode('[\D]+', str_split($phone)).')/i', strip_tags($text), $matches);

if (count($matches) > 0) {
   foreach($matches as $value) {
      $text = str_replace($value, $phone, $text);
   }
}

I try to find any non-digit characters in between the numbers but it only works if this non-digit character is between all numbers ie 0.8.8.8.1.2.3.1.2.3, but it does not match 0888-123-123. 我尝试在数字之间找到任何非数字字符,但仅当此非数字字符在所有数字之间(即0.8.8.8.1.2.3.1.2.3)时,它才有效,但与0888-123-123不匹配。 Is there some addition in this regular expression to catch the rest of the cases? 此正则表达式中是否有其他内容可以捕获其余案例?

[^\d\n]

You can try this.See demo. 您可以尝试一下。请参阅演示。

http://regex101.com/r/nB2lL9/6 http://regex101.com/r/nB2lL9/6

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM