SQL >> Databasteknik >  >> RDS >> Mysql

Markera sökresultat i text

Det finns inget behov av att överkomplicera detta. Allt du behöver göra är att ersätta varje förekomst av ett ord med det ordet paketerat i en span som bär den önskade stilen. Detta bör göra det:

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 ); // highlight word $color_index = ( $color_index + 1 ) % count( $colors ); // get next color index } return $content; // return highlighted data } 

Reguljära uttryck skulle också fungera, men str_replace() är lite snabbare.

Funktionerna tar dessa argument:

highlight_word( string, string, string );

highlight_words( string, array, array );

Exemplet ovan producerar:

Markera sökresultat i text

  1. Rankningsresultat i en MySQL-fråga med UNION ALL

  2. Hämta rader som inte matchar i MySQL

  3. MySQL – hur gör jag en skiftlägeskänslig sökning?

  4. Få sökresultat med vettig relevansordning i MySQL