The code sfullman wrote contains a bug: if $sDataValue appears three times with the same case in the search string, it
will be highlighted as
<span style="color:red;"><span style="color:red;"><span style="color:red;">...</span></span></span>
in all three places.
If you're using regular expressions, you might as well use them for the replacement as well as the search.
function HilightResults($sDataValue, $sSearchString)
{
return preg_replace('/'.preg_quote($sDataValue).'/i',
'<span style="color:red">$0</span>',
$sSearchString);
}
And since it appears from the original code that the highlighted string should be uppercased as well:
function HighlightResults_transform($match)
{
return '<span style="color:red">'.strtoupper($match[0]).'</span>';
}
function HilightResults($sDataValue, $sSearchString)
{
return preg_replace_callback('/'.preg_quote($sDataValue).'/',
'HighlightResults_transform',
$sSearchString);
}
Or, better yet,
function HilightResults($sDataValue, $sSearchString)
{
return preg_replace(
'/'.preg_quote($sDataValue).'/i',
'<span style="color:red; text-transform:uppercase;">$0</span>',
$sSearchString);
}
Which, since there isn't any need to uppercase the matched string any more, there isn't actually any need for regular expressions:
function HilightResults($sDataValue, $sSearchString)
{
return str_ireplace(
$sDataValue,
'<span style="color:red; text-transform:uppercase;">'.$sDataValue.'</span>',
$sSearchString);
}