This function will highlight search terms (Key Words in Context).
The difference between this one and the ones below is that it will preserve the original case of the search term as well. So, if you search for "american" but in the original string it is "American" it will retain the capital "A" as well as the correct case for the rest of the string.
<?php
function kwic($str1,$str2) {
$kwicLen = strlen($str1);
$kwicArray = array();
$pos = 0;
$count = 0;
while($pos !== FALSE) {
$pos = stripos($str2,$str1,$pos);
if($pos !== FALSE) {
$kwicArray[$count]['kwic'] = substr($str2,$pos,$kwicLen);
$kwicArray[$count++]['pos'] = $pos;
$pos++;
}
}
for($I=count($kwicArray)-1;$I>=0;$I--) {
$kwic = '<span class="kwic">'.$kwicArray[$I]['kwic'].'</span>';
$str2 = substr_replace($str2,$kwic,$kwicArray[$I]['pos'],$kwicLen);
}
return($str2);
}
?>