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;
if ( preg_match( '/\.google|\.bing/' , $this->referer ) )
$get_variable_name = 'q';
elseif( preg_match( '/search\.yahoo/', $this->referer ) )
$get_variable_name = 'p';
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';
}
?>
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.