highlight multiple keywords in search

前端 未结 8 489
庸人自扰
庸人自扰 2020-12-01 04:58

i\'m using this code to highlight search keywords:

function highlightWords($string, $word)
 {

        $string = str_replace($word, \"

        
8条回答
  •  日久生厌
    2020-12-01 05:22

    The other solutions may be case-insensitive in finding the highlight terms, but do not preserve their case of the original string. So searching for "st" will find "ST" but highlight it as "st", the search term.

    I use the following. It first forms the replace array, and then uses str_replace() with array parameters - which avoids recursion.

    function highlightStr($haystack, $needle, $highlightStyle) {
    
        if (strlen($highlightStyle) < 1 || strlen($haystack) < 1 || strlen($needle) < 1) {
           return $haystack;
        }
    
        preg_match_all("/$needle+/i", $haystack, $matches);
    
        $matches[0] = array_unique($matches[0]);
    
        if (is_array($matches[0]) && count($matches[0]) >= 1) {
            foreach ($matches[0] as $ii=>$match)
                $replace[$ii]="$match";
    
            $haystack = str_replace($matches[0], $replace, $haystack);
        }
    
        return $haystack;
    }
    

提交回复
热议问题