Night | Snow

Highlight Search Words in php

Posted on: February 6th, 2010

Tags: , , , ,

Many sites have opted for highlighting the keywords from their searches. This can be useful for quickly finding relavant words within large pages of text.

The following php function highlights words within html content (words in tags <> are ignored). Here you can find a live demo http://www.newsaddict.ch.

function highlight_html_content ($text, $search)
{
    $search = eregi_replace("[^-a-zA-Z0-9üäöÜÄÖèéê&']", " ", $search); // Sonderzeichen entfernen
    $search= ereg_replace ("[ ]+"," ", $search); // Doppelte Leerzeichen entfernen

    $words = explode(" ", $search); // Array mit Wörter erstellen
   
    foreach ($words as $word) {
        $w = preg_quote($word);

        $regexp = "/($w)(?![^<]+>)/iu"; // Wörter innerhalb eines Tags werden ignoriert -> i Gross-/Kleinschreibung nicht beachten -> u UTF8 damit ä=Ä ü=Ü...

        $replacement = '<b style="color:#FF0">\\1</b>';

        $text = preg_replace ($regexp,$replacement ,$text);
    }
    return $text;
}

News

Martin Fischer said:

Client and partner of simra.ch

Wir können Simon Schärer als kompetenter und zuverlässiger Programmierer höchst weiterempfehlen. Er ist nicht nur ein guter Programmierer, sondern auch ein ausgezeichneter Designer.
Danke Developer’s Island

Follow us on Twitter

favorite

I get asked a lot - which SDK should we use for web programming? I recommend Netbeans

my toolbar

Simra GameMP3 playersubscribe to RSSMy delicious bookmarksFacebookTwitterE-mail

One Response to “Highlight Search Words in php”

RSS Feed Icon  Subscribe to comments follow-up

Leave a reply

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>

Latest Tweet

loading...