Sunday 5 April 2009

Highlight of selected words in html texts

/**
 * Useful routine for text highlighting wihin search scripts
 * Searchs the selected words in the texts and highlight them
 *
 * @param   array   $texts       Array of found texts and fragments. These
 *                               may be result data recieved from any 
 *                               database or files.
 * @param   array   $words       Array of lookup words. You can pass them
 *                               from the user request forms or URL.
 * @param   array   $options
 * @return  array   Array of found original texts with highlighted words
 */
function search_hilite($texts, $words, $options=array())
{
    static $defOptions = array(
        'color' => 0xFFFFFF,
        'class' => 'hilite',
    );
    $options = array_merge($defOptions, $options);

    if (($options['color'] & 0x00FF00) < 0x008000) {
        $options['color'] = (~$options['color']) & 0xFFFFFF;
    }

    $nvcolor = (~$options['color']) & 0xFFFFFF;
    $bgcolor = $fgcolor = $options['color'];

    foreach ($words as $i => $word) {
        do {
            $bgcolor = ($bgcolor + 0x906030) & 0xFFFFFF;
        } while ($bgcolor == $options['color']);
        $fgcolor = (($bgcolor & 0x00FF00) < 0x008000) ? $options['color'] : $nvcolor;
        $search_words[$i] = "/\b($word)\b/mi";
        $hilite_words[$i] = sprintf("\\1", 
            $options['class'], 
            $bgcolor, 
            $fgcolor);
    }

    $hilite_texts = array();
    foreach ($texts as $i => $text) {
        $hilite_texts[$i] = preg_replace($search_words, $hilite_words, $text);
    }

    return $hilite_texts;
}

/**
 * Example
 */
$words = array("queen", "to be", "tomato", "that", "the", "this", "those", "these");

$texts = array(
    "tomato queen to that the this those these abracadabra tomato tomato",
    "To be or not to be",
    "That is the question",
    "\"Queen Mary\" is the drink of vodka with tomato",
    "The Pink Floyd's 'The More' album",
);

$hilite_texts = search_hilite($texts, $words);

echo '';
foreach ($hilite_texts as $text) {
    echo "
  • $text\n"; }
  • No comments:

    Post a Comment