i\'m using this code to highlight search keywords:
function highlightWords($string, $word)
{
$string = str_replace($word, \"
The other solutions may be case-insensitive in finding the highlight terms, but do not preserve their case of the original string. So searching for "st" will find "ST" but highlight it as "st", the search term.
I use the following. It first forms the replace array, and then uses str_replace() with array parameters - which avoids recursion.
function highlightStr($haystack, $needle, $highlightStyle) {
if (strlen($highlightStyle) < 1 || strlen($haystack) < 1 || strlen($needle) < 1) {
return $haystack;
}
preg_match_all("/$needle+/i", $haystack, $matches);
$matches[0] = array_unique($matches[0]);
if (is_array($matches[0]) && count($matches[0]) >= 1) {
foreach ($matches[0] as $ii=>$match)
$replace[$ii]="$match";
$haystack = str_replace($matches[0], $replace, $haystack);
}
return $haystack;
}