In PHP I need to highlight multiple given words in a string, for example wrapping found matches inside a <em>
tag.
But if I have a word ending in +
I cannot do it.
I understand the below problem is that plus is not a word and breaks that b
flag word match
. But how can I write this so that it matches and wrapps all given words even if a given word ends in +
?
$my_text = 'test c+ and javascript etc but NOT javascripter';
$words_to_highlight = array('javascript', 'c+');
foreach($words_to_highlight as $word){
$search_pattern = str_replace('+', '\+', $word);
// this doesn't match replacement
echo "n".preg_replace("/b(".$search_pattern.")b/i", '<em>$1</em>', $my_text);
// works if I remove the b flag, but I don't want to match "javascript" inside "javascripter"
echo "n".preg_replace("/(".$search_pattern.")/i", '<em>$1</em>', $my_text);
}
Output is:
test c+ and <em>javascript</em> etc but NOT javascripter
test c+ and <em>javascript</em> etc but NOT <em>javascript</em>er
test c+ and javascript etc but NOT javascripter
test <em>c+</em> and javascript etc but NOT javascripter
What I want to result is:
test <em>c+</em> and <em>javascript</em> etc but NOT javascripter