Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / PHP

Catching Keywords from Search Engines

3.67/5 (3 votes)
3 Feb 2010CPOL 4.6K  
There is a bug with your regex.Say for example that you were refered to by google.uk/search?q=example&ie=utf-8, your code would return 'example'. If, however, you were refered to by google.uk/search?q=example, it would return 'oops'.The simple fix is to change the limitation variable from...
There is a bug with your regex.
Say for example that you were refered to by google.uk/search?q=example&ie=utf-8, your code would return 'example'. If, however, you were refered to by google.uk/search?q=example, it would return 'oops'.

The simple fix is to change the limitation variable from & to (&|$).

The following is the testbed I used.
PHP
<?php
class SearchEngineKeywords
{
    private $referer;

    public function __construct( $search_string = null )
    {
        $referer = isset( $search_string ) && is_string( $search_string )
            ? $search_string : ( isset( $_SERVER[ 'HTTP_REFERER' ] )
                ? $_SERVER[ 'HTTP_REFERER' ] : null );

        if ( isset( $referer ) && preg_match( '/\.google|search\.yahoo|\.bing/' , $referer ) )
            $this->referer = urldecode( $referer );
    }

    public function get_keywords()
    {
        if ( !isset( $this->referer ) )
            return false;

        // Google and Bing
        if ( preg_match( '/\.google|\.bing/' , $this->referer ) )
            $get_variable_name = 'q';

        // Yahoo
        elseif( preg_match( '/search\.yahoo/', $this->referer ) )
            $get_variable_name = 'p';

        // Default
        else
            return false;

        return preg_match( '/' . $this->get_separators() . $get_variable_name . '=(.+?)(&|$)/si' , $this->referer , $keywords ) == 0
            ? false : $keywords[1];
    }

    private function get_separators()
    {
        return preg_match( '/\?q=|\?p=/' , $this->referer ) ? '\?' : '&';
    }
}
?>
The previous code was tested by:
PHP
<?php
$SearchEngineKeywords = new SearchEngineKeywords( 'http://www.google.co.uk/search?q=example' );

if ( $keywords = $SearchEngineKeywords->get_keywords() )
{
	echo $keywords;
}
else
{
	echo 'ooops';
}
?>

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)