highlight multiple keywords in search

前端 未结 8 438
庸人自扰
庸人自扰 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:40

    Assuming the words are entered as a space seperated string you can just use explode

    $words = explode(' ', $term);
    

    Although if you want to ensure there are not multiple spaces, you may want to remove them from the string first

    $term = preg_replace('/\s+/', ' ', trim($term));
    $words = explode(' ', $term);
    

    You do then have to generate a replacement array

    $highlighted = array();
    foreach ( $words as $word ){
        $highlighted[] = "<span class='highlight'>".$word."</span>"
    }
    

    Then

    str_replace($words, $highlighted, $string);
    

    So putting it togther

    function highlightWords($string, $term){
        $term = preg_replace('/\s+/', ' ', trim($term));
        $words = explode(' ', $term);
    
        $highlighted = array();
        foreach ( $words as $word ){
            $highlighted[] = "<span class='highlight'>".$word."</span>"
        }
    
        return str_replace($words, $highlighted, $string);
    }
    
    0 讨论(0)
  • 2020-12-01 05:43

    here is simple function to highlight only match text.

    function highlighter_text($text, $words)
    {
        $split_words = explode( " " , $words );
        foreach($split_words as $word)
        {
            $color = "#e5e5e5";
            $text = preg_replace("|($word)|Ui" ,
                "<span style=\"background:".$color.";\"><b>$1</b></span>" , $text );
        }
        return $text;
    }
    

    call function

    0 讨论(0)
提交回复
热议问题