Google Hilite · 30 November 2002

I saw that young (the hardest working human in modern pediatrics) had implemented a very suave bit of scripting, one that highlights the search terms that bring people to his site via Google.

I was like WHOAH DOOD and he was all LAHLAH LOOK AT ME and I was all NOT EVEN and he was all LOOKIT MY GOOGLE THING and I’m like NO WAY DOOD and he’s like NYAH NYAH and I’m like

<?php
function google_hilite($text) {
$ref = urldecode($_SERVER[HTTP_REFERER]);
if (preg_match('/^http:\/\/w?w?w?\.?google.*/i',$ref)) {
$query = preg_replace('/^.*q=([^&]+)&?.*$/i','$1',$ref);
$query = preg_replace('/\'|"/','',$query);
$query_array = preg_split ("/[\s,\+\.]+/",$query);
foreach($query_array as $b){
if (!preg_match('/<.+>/',$text)) {
$text = preg_replace(
'/(\b'.$b.'\b)/i',
'<span class="hilite">$1</span>',
$text);
} else {
$text = preg_replace(
'/(?<=>)([^<]+)?(\b'.$b.'\b)/i',
'$1<span class="hilite">$2</span>',
$text);
}
}
}
return $text;
}
?>

Some documentation and an ancillary script are here.

To see Google Hilite in action, click through the first result on a Google search for (after the ‘sponsored link’) or the fifth (!) result for .

NB: The examples cited above weren’t working for a few hours on Sunday, owing to a cockup by the author.

UPDATE: Using this is much simpler than I may have indicated. Google Hilite can be used on just about any page, so long as PHP is running on the server. Further details and a download.

*   *   *