Extensible search highlighting in PHP
Based on Dean's original Google Hilite, but refactored a bit to make it easy to add support for more search engines (currently supports some 20-odd major searches).)([^<]+)?(\b'.$term.'\b)/i', $text)) { $matched = "Spoon!"; } else { $mismatched = "Whoops"; } if (!preg_match('/<.+>/',$text)) { $text = preg_replace('/(\b'.$term.'\b)/i','$1',$text); } else { $text = preg_replace('/(?<=>)([^<]+)?(\b'.$term.'\b)/i','$1$2',$text); } } $query_terms = implode(" ", $query_array); $query_terms = htmlspecialchars(urldecode($query_terms)); //If all terms matched, just tell them you did the highlighting. if($matched) { //Change this message if you like. $message = "It seems you arrived at this page from a search engine. To help you find " . "what you were looking for, your search terms (\"$query_terms\") should " . "be highlighted with yellow backgrounds, like this.
"; $text = $message . $text; } elseif($mismatched) { //If only some or no terms matched, offer to repeat the search locally. $query = implode("+", $query_array); //Also change this message if you like. $message = "It seems you arrived at this page from a search engine, but that some " . "or all of the terms you searched for (\"$query_terms\") aren’t in this page. Would you like to " . "try your search again using this site’s built-in search? It might be more accurate.
"; if($matched) { $message .= "Any of your search terms which do appear in this page " . "should be highlighted with yellow backgrounds, like this.
"; } $text = $message . $text; } } return $text; } ?>