从具有超过6位数的正则表达式php的字符串中替换单词

时间:2016-06-10 22:50:24

标签: php regex preg-match

我想替换超过6位数的字符串中的所有单词。

示例:

'我的联系人号码是(432)(323)(322)。我的另一个号码是+1239343。另一个是343as32240'

TO:

'我的联系人号码已被删除。我的另一个号码是[已删除]。另一个被[删除]'

我知道正则表达式和preg_replace。只需要正确的正则表达式。

1 个答案:

答案 0 :(得分:5)

您可以使用此正则表达式进行搜索:

(?<=\h|^)(?:[^\h\d]*\d){6}\S*

并替换为[removed]

<强>解体:

(?<=\h|^)      # loookbehind to assert previous position is line start or whitespace
(?:            # start of non capturing group
   [^\h\d]*\d  # 0 or more non-space and non-digits followed by 1 digit
)              # end of non capturing group
{6}            # match 6 of this group
\S*            # followed by 0 or more non-space characters

<强>代码:

$result = preg_replace('/(?<=\h|^)(?:[^\h\d]*\d){6}\S*/', '[removed]', $str);

RegEx Demo