Hello All, I am looking to write code which displays: from which keyword search a person landed on my website and highlighting them, if somebody has written it already, it would be really great if u can share Or can you please guide me how to go about it. Thanks in Advance, PHP Newbie.
<?php $your_text = 'Your text. Here will the keywords be highlighted.'; @extract(@parse_url($_SERVER['HTTP_REFERER'])); if (preg_match('/((fr|g)oogle|msn|yahoo|alexa)/i', $host) AND preg_match('/q(uery)?=([^&]+)/i', $query, $keywords)) { $keywords = array_unique(preg_split('/[\s\+]+/', rawurldecode($keywords[2]), -1, PREG_SPLIT_NO_EMPTY)); foreach ($keywords AS $keyword) { $your_text = preg_replace('/('. preg_quote($keyword) .')/i', '<span style="color: red; font-weight: bold;">$1</span>', $your_text); } } echo $your_text; ?> PHP: Give this a try.
Try this! if you need to run on server please comment first line and uncomment second line $url <?php $url="http://www.google.com/search?q=spyware&meta="; //$url=$_SERVER['HTTP_REFERER']; @extract(@parse_url($url)); if (preg_match('/((fr|g)oogle|msn|yahoo|alexa)/i', $host) AND preg_match('/q(uery)?=([^&]+)/i', $query, $keywords)){ $keywords = array_unique(preg_split('/[\s\+]+/', rawurldecode($keywords[2]), -1, PREG_SPLIT_NO_EMPTY)); foreach ($keywords as $keyword) { echo "You come from $host with keyword [".$keyword."]"; } } ?> PHP:
Thanks ColdMoney, it did run, but i faced 2 issues, 1. It doesnt work for multiple keywords Correct me if I am wrong, its got to do somthing with regular expression and 2. It aint highlighting the keyword on the page. I will try my R&D tomorrow.
I made a fuction of it. <?php function highlight_search_keywords($text) { @extract(@parse_url($_SERVER['HTTP_REFERER'])); if (preg_match('/((fr|g)oogle|msn|yahoo|alexa)/i', $host) AND preg_match('/[qp]=([^&]+)/i', $query, $keywords)) { $keywords = preg_split('/[\s\+\,]+/', rawurldecode($keywords[1]), -1, PREG_SPLIT_NO_EMPTY); foreach (array_unique($keywords) AS $keyword) { $text = preg_replace('/('. preg_quote($keyword) .')/i', '<span style="color: red; font-weight: bold;">$1</span>', $text); } } return $text; } ?> PHP: http://www.bytemycode.com/snippets/snippet/588/ It's easier to use this way. And yes, it highlights multiple keyworlds.