Click here to Skip to main content
11,641,416 members (65,339 online)
Click here to Skip to main content

Tagged as

Catching Keywords from Search Engines

, 3 Feb 2010 CPOL 1.5K 2
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)

Share

About the Author

fly904
Software Developer
United Kingdom United Kingdom
No Biography provided

You may also be interested in...

Comments and Discussions

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