在php中不区分大小写突出显示

inp*_*put 3 php search highlight case-insensitive

我正在使用此函数来突出显示mysql查询的结果:

 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);
Run Code Online (Sandbox Code Playgroud)

问题是,如果我输入'good',它只会显示我的搜索结果,小写'g'ood而不是'Good'.我该怎么纠正这个?

ser*_*erg 19

str_ireplace()改用.

编辑:这是regexp版本,保留原始案例:

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

  • 你应该使用`preg_quote($ word,'/')`而不仅仅是'$ word`. (3认同)