Search code examples
phpsearchhighlightcase-insensitive

case insensitive highlighting in php


i'm using this function to highlight the results from mysql query:

 function highlightWords($string, $word)
 {

        $string = str_replace($word, "<span class='highlight'>".$word."</span>", $string);
    /*** return the highlighted string ***/
    return $string;

 }

 ....

  $cQuote =  highlightWords(htmlspecialchars($row['cQuotes']), $search_result);

the problem is, if i type in 'good', it will only show my search results with a lower-case 'g'ood and not 'Good'. how do i rectify this?


Solution

  • Use str_ireplace() instead.

    EDIT: Here is regexp version that keeps original case:

    $string = preg_replace("/".preg_quote($word, "/")."/i", "<span class='highlight'>$0</span>", $string);