Nguyen Duc Thuan's Homepage » PHP »

PHP: How To Highlight Search Without Affecting HTML Tags

This class enables you to highlight keywords in the search results without affecting HTML tags. It can exactly highlight the string in double quotes of the keyword. For example:

$highlightedString = Fete_Util_Text_Highlighter::createInstance('<b>', '</b>')
->highlight('PHP rules the world', '"PHP rules" world'); // prints <b>PHP rules</b> the <b>world</b>

The class has been updated at http://www.phpclasses.org/browse/package/5471.html, it now can ignore the text within <style> and <script> tags, follow that link to get updates. If you found any problem, please report it to me. Thanks.

Usage:

To create new instance:

$highlighter = new Fete_Util_Text_Highlighter();

or:

$highlighter = Fete_Util_Text_Highlighter::createInstance();

To change the text before and after keyword match:

$highlighter->setBeforeMatch('<strong>')->setAfterMatch('</strong>');

To get the keyword-highlighted text:

$highlighted = $highlighter->highlight($originalText, $yourKeyword);

Related Posts

No related posts.

Share and enjoy:
Design BumpDeliciousDiggFacebookDesign FloatMixxRedditStumbleUponTechnoratiTwitter

4 Responses to “PHP: How To Highlight Search Without Affecting HTML Tags”

  1. ceasar says:

    Hai Nguyen,
    Great script and works :)
    However it doesn’t escape words in
    example

    var so = new SWFObject("http://www.youtube.com/v/Wgr8H20b0sM&hl=nl&iv_load_policy=3&showinfo=0&showsearch=0&fs=1&rel=0&border=0&color1=0xBFCCA6&color2=0xBFCCA6", "youtube_Wgr8H20b0sM", "425", "350", "9", "");

    You will see the word youtube be highlighted.
    Is there a fix that it skips all the content between

    Thanks for looking in

  2. ceasar says:

    The code postesd isn’t complete
    http://www.youtube.com/v/Wgr8H20b0sM

  3. ceasar says:

    The code example in this blog isn’t correct
    See http://www.phpclasses.org/discuss/package/5471/

  4. ndthuan says:

    My name is Thuan Nguyen, not Hai Nguyen :D

    I’ve replied your messages at phpclasses.org

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>