php preg_replace电话号码 - php

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

<a>click here now! (123) -456-789</a>

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

$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
}

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

参考方案

我认为这将匹配两组三位数字和一组四位数字,介于两者之间的“常用”电话号码标点符号:

\d{3}[().-\s[\]]*\d{3}[().-\s[\]]*\d{4}

这允许三个数字,然后是任意数量的标点符号或空格,然后是三个数字,然后是更多标点符号,然后是四个数字。

但是,如果没有更好地了解输入格式的信息,您将永远无法真正确定仅会获得电话号码,而不会获得其他任何东西,或者您不会跳过任何电话号码。

如果您想用自己的号码替换找到的号码,我可以尝试这样的操作:

preg_replace('/\d{3}([().-\s[\]]*)\d{3}([().-\s[\]]*)\d{4}/',
    "123$1456$27890", $input);

在替换字符串中,$1$2是数字之间的两个带括号的标点符号。这样,您可以只替换找到的数字,而通过将相同的标点插入到结果字符串中来保留标点。

php preg_replace两个或更多空格 - php

我正在寻找替换多个空格字符的实例。我最初的搜索似乎都集中在使用/s,但这包括换行符和其他空格我认为应该接近吗?用一个空格替换两个或更多实例空格" "preg_replace('/ {2,}/', ' ', $string); 参考方案 尝试一下:preg_replace('/\s\s+/&…

PHP:Preg_replace,单词边界和非单词字符 - php

我需要替换文本中以井号(#)开头的单词。好吧,我知道如何替换整个单词。preg_replace("/\b".$variable."\b/", $value, $text);由于该\ b修饰符仅接受单词字符,因此不会替换包含井号的单词。我有这个html,其中包含#companyName类型的变量,我将其替换为一个值。 参…

PHP preg_replace删除字符串中的第一个HTML元素 - php

我想在PHP中删除html字符串(始终是一个段落)的整个第一个元素。我目前的方法是使用:$passage = preg_replace('/.*?\b'.'</p>'.'\b/s', '', $passage, 1); 由于</p>中的特殊字符,此方法不起…

PHP preg_match直到双行中断 - php

我在mysql字段中有此数据:First text text text text text text text text text text text text text text text text text text text text Second text text text text text text text text text text te…

PHP preg_replace和号 - php

好吧,我可能不会以正确的方式解决这个问题,但是这里就来了。我有这个带链接的字符串,并提取标签之间的文本...$string = $item; $pattern = '/\<a([^>]*)\>([^<]*)\<\/a\>/i'; $replacement = '$2'; $messa…