The following php function will highlight a substring (or keyword) within another string, and is very useful for search results and displaying what a user searched for. The function wraps the keyword (if found) in a css class which can then be customised to quickly show the user the keyword in search results for example.
Usage: echo highlight('This is the input string, this is the keyword.','keyword');
Outputs: This is the input string, this is the keyword.
This function is on no way complete and if you notice any errors/improvements please let me know, I have found this function very useful and easy to use compared to some of the others out there that rely on regular expressions and dont take into account the case of the keyword.
/**
* highlight_keyword
*
* Highlight a keyword (needle) in searchstring (haystack) by adding a css class to the found word
*
* @param $haystack string The string to search within
* @param $needle string The string to search for
* @return string
*/
function highlight($haystack,$needle){
$match=strrpos(strtolower($haystack),strtolower($needle));
if (is_numeric($match)){
$len=strlen($needle);
$total = mb_strlen($haystack);
$new_string_1="";
$new_string_2="<span class='keyword_highlight'>";
for ($k = 0; $k < $total; $k++) {
$char = mb_substr($haystack, $k, 1);
if ($k < $match){
$new_string_1.=$char;
}elseif ($k==($match + $len)){
$new_string_2.=$char . "</span>";
}else{
$new_string_2.=$char;
}
}
return $new_string_1 . $new_string_2 . "";
}else{
return $haystack;
}
}
This page was last updated: 04 Jan 2012