Mysql
 sql >> Database >  >> RDS >> Mysql

come evidenziare i risultati di ricerca

Non dovresti renderlo troppo difficile per te stesso. Tutto ciò che serve per sostituire ogni occorrenza di una parola con la parola racchiusa nell'intervallo con lo stile richiesto applicato. Questo dovrebbe funzionare per te:

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>';
}

Andrebbe bene anche l'uso di espressioni regolari per sostituire il contenuto, sebbene si utilizzi str_replace() è un po' più veloce.

Le funzioni accettano questi argomenti:

highlight_word( string, string, string );

highlight_words( string, array, array );

L'esempio precedente risulta in: