M Hussain M Hussain - 5 months ago 9
PHP Question

replace words from string having more than 6 digits regex php

I want to replace all words from a string having more than 6 digits.

Example:

'my contact no is (432)(323)(322). my other number is +1239343. another one is 343as32240'

TO:

'my contact no is [removed]. my other number is [removed]. another one is [removed]'

I am aware of regex and preg_replace. Just need correct regex for this.

Answer

You can use this regex for search:

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

and replace by [removed].

Breakup:

(?<=\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

Code:

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

RegEx Demo