Click here to Skip to main content
15,861,125 members
Articles / Programming Languages / PHP
Alternative
Tip/Trick

Catching Keywords from Search Engines

Rate me:
Please Sign up or sign in to vote.
3.67/5 (3 votes)
3 Feb 2010CPOL 4.5K   2  
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)


Written By
Software Developer
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --