Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Highlight words in string

I have a bunch of text and i want to highlight some words on that text. I've search the stackoverflow website and came up with something that almost work.

PHP

function highlighter($str, $arr_word)
{
    foreach($arr_word as $vword) {
        $text = preg_replace("|($vword)|Ui", "<span class=highlight>$1</span>", $str);
    }

    return $text;
}

$lyrics = 'hello looking for';
$arr_accepted_keyword = array('hello', 'for');

echo highlighter($lyrics, $arr_accepted_keyword);

For some reason, it always highligths the last word, and not all the words. Why?

like image 217
Marco Avatar asked Aug 24 '26 05:08

Marco


1 Answers

The problem is that you're highlighting each word in the original string, not the updated string.

function highlighter($str, $arr_word)
{
    foreach($arr_word as $vword) {
        $str = preg_replace("/($vword)/Ui", "<span class=highlight>$1</span>", $str);
    }

    return $str;
}

$lyrics = "hello, is it me you're looking for?";
$arr_accepted_keyword = array('hello', 'for');

echo highlighter($lyrics, $arr_accepted_keyword);
// "<span class=highlight>hello</span>, is it me you're looking <span class=highlight>for</span>?"
like image 166
samlev Avatar answered Aug 26 '26 22:08

samlev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!