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?
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>?"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With