How can I replace multiple words without using STR_REPLACE?

2

For example, I want to sweat a text.

How can I do it using the substitution method? Something that is faster.

Using str_replace() is not very fast.

    
asked by anonymous 29.01.2016 / 18:10

1 answer

1

You can use preg_replace_callback() it is fast.

In the case of wanting to substitute bad words for '*' here is a good example:

$badwords = array('bad1', 'bad2', 'bad3', 'ass');
$text = 'This is a test. Ass. Grass. bad1.';

function filterBadwords($text, array $badwords, $replaceChar = '*') {
    return preg_replace_callback(
        array_map(function($w) { return '/\b' . preg_quote($w, '/') . '\b/i'; }, $badwords),
        function($match) use ($replaceChar) { return str_repeat($replaceChar, strlen($match[0])); },
        $text
    );
}

echo filterBadwords($text, $badwords);

or echo will print:

  

This is a test. ***. Grass. ****.

If on the other hand instead of replacing you want to highlight the words you can use this function:

$badwords = array('bad1', 'bad2', 'bad3', 'ass');
$text = 'This is a test. Ass. Grass. bad1.';

function badwords_filter($string,$badwords){
        $p = implode('|', array_map('preg_quote', $words ));
        $string = preg_replace(
            '/('.$p.')/i', 
            '<span style="background:#fe5723; color:#fff">$1</span>', 
            $string
        );   
    return $string; 
}

echo badwords_filter($text, $badwords);
    
10.02.2016 / 14:09