简体   繁体   中英

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 fox jumps around the box" or "Jumping fox jumps around the box"

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM