Reputation: 485
I picked up this code from stackoverflow to bold matched keywords. But it only bold exactly matched keywords.
For example:
$text = "iphone" and $srch_term = "iphone" -> matched and bold it
$text = "iphone" and $srch_term = "iph" -> No matched (I would like it to be matched and bold as well)
How can i fix this code below to achieve this goal? Sorry I have limited knowledge of using regex so I am not sure what to do with it.
function highlightWords($text, $srch_term) {
preg_match_all('~\w+~', $srch_term, $m);
if(!$m)
return $text;
$re = '~\\b(' . implode('|', $m[0]) . ')\\b~i';
return preg_replace($re, '<b>$0</b>', $text);
}
Upvotes: 1
Views: 25
Reputation: 67978
$re = '~(' . implode('|', $m[0]) . ')~i';
Use this.Remove \b
as it will look for word boundaries.
\b assert position at a word boundary (^\w|\w$|\W\w|\w\W)
Upvotes: 2