Search code examples
phpregexlaravelpreg-replacepreg-match

Replace string that is separated by whitespace or other special character in PHP


I need to find a way to find part of the string in text and to replace it with ***

For example, I have text "Jumping fox jumps around the box" in normal cases, I would use:

preg_replace('/\b(fox)\b/i', '****', "fox");

but I want to cover cases when we have text "Jumping f.o.x jumps around the box" or "Jumping f o x jumps around the box"

So basically, I would need regex to support that kind of searches... to cover more special characters is even better


Solution

  • One way would be to add the class of to be ignored chars between each char of the search string. This could be done with simple php functions

    $string = 'Jumping f.o.x jumps around the box';
    $word = 'fox';
    $ignore = '[\s\.]*';
    $regex = '/\b' . join($ignore, str_split($word)) . '\b/i';
    $new_string = preg_replace($regex, '***', $string);
    

    If your word contains some regex special chars, you might want to apply preg_quote to each char.

    join($ignore, array_map(function($char) {
        return preg_quote($char, '/');
    }, str_split($word)));