views:

1388

answers:

3

Hi,

I am trying to get the search keyword from a referrer url. Currently, I am using the following code for Google urls. But sometimes it is not working...

$query_get = "(q|p)";
$referrer = "http://www.google.com/search?hl=en&q=learn+php+2&client=firefox";
preg_match('/[?&]'.$query_get.'=(.*?)[&]/',$referrer,$search_keyword);

Is there another/clean/working way to do this?

Thank you, Prasad

+2  A: 

If you're using PHP5 take a look at http://php.net/parse%5Furl and http://php.net/parse%5Fstr

Example:


// The referrer
$referrer = 'http://www.google.com/search?hl=en&q=learn+php+2&client=firefox';

// Parse the URL into an array
$parsed = parse_url( $referrer, PHP_URL_QUERY );

// Parse the query string into an array
parse_str( $parsed, $query );

// Output the result
echo $query['q'];
William
Thank you for the quick answer...
pnm123
No problem, if your question is answered please click the check under the correct answer so everyone knows it's answered.
William
A: 
$query = parse_url($request, PHP_URL_QUERY);
powtac
Updated my post to add the second parameter. I was hoping he'd lookup the method to see how it works on his own but oh well.
William
A: 

There are different query strings on different search engines. After trying Wiliam's method, I have figured out my own method. (Because, Yahoo's is using 'p', but sometimes 'q')

$referrer = "http://search.yahoo.com/search?p=www.stack+overflow%2Ccom&ei=utf-8&fr=slv8-msgr&xargs=0&pstart=1&b=61&xa=nSFc5KjbV2gQCZejYJqWdQ--,1259335755";
$referrer_query = parse_url($referrer);
$referrer_query = $referrer_query['query'];
$q = "[q|p]"; //Yahoo uses both query strings, I am using switch() for each search engine
preg_match('/'.$q.'=(.*?)&/',$referrer,$keyword);
$keyword = urldecode($keyword[1]);
echo $keyword; //Outputs "www.stack overflow,com"

Thank you, Prasad

pnm123
In my example you could also check to see if the array key q or p were present, and if so use that instead of the other. To be honest, I recommend checking the domain it's coming from and working with the the data based off that. As of right now ANYONE coming from ANY site with "q" or "p" would look like it came from Google/Yahoo.
William
To prevent that, I am using this >>> if(preg_match('/[\.\/](google|yahoo|bing|geegain|mywebsearch|ask|alltheweb)\.[a-z\.]{2,5}[\/]/i',$referrer,$search_engine)){ <<<
pnm123