Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get keyword from a (search engine) referrer url using PHP

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

like image 467
Prasad N Avatar asked Nov 26 '09 19:11

Prasad N


2 Answers

If you're using PHP5 take a look at http://php.net/parse_url and http://php.net/parse_str

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'];
like image 117
William Avatar answered Oct 03 '22 18:10

William


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

like image 45
Prasad N Avatar answered Oct 03 '22 20:10

Prasad N