how to highlight search results

前端 未结 3 2075
野的像风
野的像风 2020-12-21 01:55

hello i have a search function in that i will search a db for keywords. i would like to highlight the keywords and found a second function that i would like to implement int

3条回答
  •  春和景丽
    2020-12-21 02:32

    You shouldn't make it too hard for yourself. All you need it to replace every occurrence of a word with the word wrapped in the span with the required style applied. This should work for you:

    function highlight_word( $content, $word, $color ) {
        $replace = '' . $word . ''; // create replacement
        $content = str_replace( $word, $replace, $content ); // replace content
    
        return $content; // return highlighted data
    }
    
    function highlight_words( $content, $words, $colors ) {
        $color_index = 0; // index of color (assuming it's an array)
    
        // loop through words
        foreach( $words as $word ) {
            $content = highlight_word( $content, $word, $colors[$color_index] ); // highlight word
            $color_index = ( $color_index + 1 ) % count( $colors ); // get next color index
        }
    
        return $content; // return highlighted data
    }
    
    
    
    // words to find
    $words = array(
        'normal',
        'text'
    );
    
    // colors to use
    $colors = array(
        '#88ccff',
        '#cc88ff'
    );
    
    // faking your results_text
    $results_text = array(
        array(
            'ab'    => 'AB #1',
            'cd'    => 'Some normal text with normal words isn\'t abnormal at all'
        ), array(
            'ab'    => 'AB #2',
            'cd'    => 'This is another text containing very normal content'
        )
    );
    
    // loop through results (assuming $output1 is true)
    foreach( $results_text as $result ) {
        $result['cd'] = highlight_words( $result['cd'], $words, $colors );
    
        echo '

    ab: ' . $result['ab'] . '
    cd: ' . $result['cd'] . '

    '; }

    Using Regular Expressions to replace content would do as well, though using str_replace() is a bit faster.

    The functions accepts these arguments:

    highlight_word( string, string, string );

    highlight_words( string, array, array );

    The above example results in:

    enter image description here

提交回复
热议问题