function highlight_phrase($str, $phrase, $class='highlight')
{
if ($str == '')
{
return '';
}
if ($phrase != '')
{
return preg_replace('/('.preg_quote($phrase, '/').')/Ui', '<span class="'.$class.'">'."\\1".'</span>', $str);
}
return $str;
}
above code is what i use to highlight phrases in a string. I have problem with following issues:
-
if phrase is new car it matches new car and new cars both in a string meaning it highlights new car of new cars but i need not highlight new cars.
-
I could check for space but what if phrase ends with ,.? or ! etc.
Use the
\bpattern to match word boundaries, i.e. in your case/\b(new car)\b/will matchbut not