highlight multiple keywords in search

前端 未结 8 471
庸人自扰
庸人自扰 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[] = "".$word.""
    }
    

    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[] = "".$word.""
        }
    
        return str_replace($words, $highlighted, $string);
    }
    

提交回复
热议问题