Click here to Skip to main content
Click here to Skip to main content
Alternative Tip

Catching Keywords from Search Engines

, 3 Feb 2010
Rate this:
Please Sign up or sign in to vote.
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
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
$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)

About the Author

fly904
Software Developer
United Kingdom United Kingdom
No Biography provided

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web03 | 2.8.140709.1 | Last Updated 3 Feb 2010
Article Copyright 2010 by fly904
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid