Sheremet
Sheremet

Reputation: 32

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

Upvotes: 0

Views: 229

Answers (2)

Sheremet
Sheremet

Reputation: 32

This is final function.

if (! function_exists('preg_replace_word')) {

    function preg_replace_word($search, $replace, $string)
    {
        $ignore = '[\s\._-]*';
        $regex = '/\b' . join($ignore, str_split($search)) . '\b/i';
        return preg_replace($regex, $replace, $string);
    }
}

Upvotes: 0

Philipp
Philipp

Reputation: 15629

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)));

Upvotes: 1

Related Questions