case insensitive highlighting in php

江枫思渺然 提交于 2019-12-01 06:39:02

问题


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?


回答1:


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);


来源:https://stackoverflow.com/questions/2750736/case-insensitive-highlighting-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!