how to highlight search results

前端 未结 3 2051
野的像风
野的像风 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:25

    By using str_ireplace instead of str_replace, the function will work case insensitive

    0 讨论(0)
  • 2020-12-21 02:30

    I would not use the SQL method. As time goes on, and you have more and more highlighting rules, that will become unmanageable. Also trickier to handle the cases where you need to highlight foo differently to foobar, but one contains the other.

    Separate your data handling from your formatting.

    0 讨论(0)
  • 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 = '<span style="background-color: ' . $color . ';">' . $word . '</span>'; // 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 '<fieldset><p>ab: ' . $result['ab'] . '<br />cd: ' . $result['cd'] . '</p></fieldset>';
    }
    

    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

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