Page is a not externally linkable
andreasfriedrich - 8:12 pm on Mar 11, 2003 (gmt 0)
Highlighting the terms searched for in Google or Yahoo on your own page is really easy. It involves reading the Referrer string, parsing the search terms and searching for those terms in the text on your page. If you get your text from a database all you need to do is run the text through the following code after retrieving it from the database. But even for other methods of generating your page there is an easy solution that we have already used to Get rid of those query strings [webmasterworld.com]. If you put the following code into the output buffering callback function you specified with ob_start() [php.net] all search terms in all of PHP [php.net]´s output will be highlighted. Code Put this code either into your output buffering callback function or use it on text retrieved from a database. How it works If If $terms is unequal '' we split the search terms on whitespace (\s) or plus (+) into separate words and then loop over the array of terms and build a regular expression for each term. To continue the example from above our $terms array will look like this: The terms array is then fed into the preg_replace() [php.net] function which will replace it in $line with <em>\1</em>. A text like Aaron Carter rules! will get changed to read <em>Aaron</em> <em>Carter</em> rules!. Some improvements The above code will emphasize search terms but there is no way to distinguish between search terms. To achieve that you might want to build a parallel $replacement array which contains entries like these <em class="one">Aaron</em> and <em class="two">Carter</em>. The preg_replace() [php.net] line would then read: Beware though that this will add quite a bit of processing to each request coming from a search engine. The nice effect it might have on your visitors may or may not make up for that slow down. Andreas
Highlighting Search Terms
if (preg_match [php.net]("'google\.¦brisbane\.'", $_SERVER['HTTP_REFERER'])) {
preg_match [php.net]("'q=([^&]+)'", $_SERVER['HTTP_REFERER'], $match);
$terms = $match[1];
} elseif (preg_match [php.net]("'yahoo\.'", $_SERVER['HTTP_REFERER'])) {
preg_match [php.net]("'p=([^&]+)'", $_SERVER['HTTP_REFERER'], $match);
$terms = $match[1];
}
if ($terms!= '') {
$terms = preg_split [php.net]('/\s+¦\++/', $terms);
for($i=0;$i<count [php.net]($terms);$i++) {
$terms[$i] = "'\b(" . preg_quote [php.net](htmlentities [php.net]($terms[$i]), "'")
. ")\b'i";
}
$line = preg_replace [php.net]($terms, "<em>\\1</em>", $line);
} $_SERVER['HTTP_REFERER'] contains either Google¦Brisbane¦Yahoo we retrieve the search terms from the query string and store them in $terms. Given a referrer of http://www.google.de/search?q=Aaron+Carter&ie=ISO-8859-1&hl=de&meta= $terms will contain Aaron+Carter.
$terms[0] = "'\b(Aaron)\b'";
$terms[1] = "'\b(Carter)\b'";
$line = preg_replace [php.net]($terms, $replacements, $line);