Return to Snippet

Revision: 60012
at October 16, 2012 00:52 by pruntrut


Initial Code
function HighlightTerms($text_string,$keywords) {
    //this function searches for words from the keywords, and finds matches in the text,
    //and highlights (bolds) them. like google does.
 
    // $text_sting:    the text from which you want to highlight and return...
    // $keywords:      either string or array or words that should be highlighted in the text.
 
    if (!is_array($keywords)) {
        //explode the keywords
        $keywords = explode(" ",$keywords);
    }
    //find matches
    for ($x=0;$x<count($keywords);$x++) {
        if (strlen($keywords[$x]) > 1) {
            preg_match_all ("'" . $keywords[$x] . "'si", $text_string, $items);
            for ($y=0;$y<count($items);$y++) {
                if (isset($items[$y][0])) {
                    $text_string = str_replace($items[$y][0],'<span class="highlight">' . $items[$y][0] . '</span>',$text_string);
                }
            }          
        }
    }
    return $text_string;
}

Initial URL

                                

Initial Description
Highlight Search Terms in Text

Initial Title
Highlight Search Terms in Text

Initial Tags
php

Initial Language
PHP