Highlight Search Words in php
Posted on: February 6th, 2010
Tags: eregi_replace, ereg_replace, preg_replace, Regex, RegularExpressions
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.
{
$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;
}
Posted in Code Snippets,Php | Trackback Url








One Response to “Highlight Search Words in php”
1 Trackbacks/Pingbacks
Leave a reply