Mysql
 sql >> Base de données >  >> RDS >> Mysql

comment mettre en évidence les résultats de recherche

Vous ne devriez pas vous compliquer la tâche. Tout ce dont vous avez besoin pour remplacer chaque occurrence d'un mot par le mot enveloppé dans la durée avec le style requis appliqué. Cela devrait fonctionner pour vous :

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

L'utilisation d'expressions régulières pour remplacer le contenu ferait également l'affaire, mais en utilisant str_replace() est un peu plus rapide.

La fonction accepte ces arguments :

highlight_word( string, string, string );

highlight_words( string, array, array );

L'exemple ci-dessus donne :