Link to home
Start Free TrialLog in
Avatar of webgeek154
webgeek154Flag for United States of America

asked on

Parse out a parameter in a url (PHP)

Hi Experts!

I'm trying to parse out a certain parameter in the string stored at $_SERVER['HTTP_REFERER'].

Here's are examples of what that string looks like:

http://www.google.com/search?hl=en&q=marriage+problems&revid=486951557&sa=X&oi=revisions_inline&resnum=0&ct=top-revision&cd=1

http://www.google.com/search?sourceid=navclient&ie=UTF-8&rlz=1T4HPND_enUS213US214&q=relationship+counseling+sturbridge

http://www.google.com/search?hl=en&q=marriage+counseling

The parameter of interest is 'q'.  I want to grab that parameter and store it into $_SESSION['query']

I know I can figure this out on my own but it would probably take me hours to figure out and it would probably be a sub-optimal solution.

Thanks!
John
Avatar of hielo
hielo
Flag of Wallis and Futuna image

preg_match('/q=([^&]*)/', $_SERVER['HTTP_REFERER'],$match);
print_r( $match );
Avatar of webgeek154

ASKER

Thanks Hielo,

Do you think you can explain the regular expression in that first parameter of the preg_match() function?

I am VERY new to programming so it's like jibberish to me.  : )

Thanks!
John
ASKER CERTIFIED SOLUTION
Avatar of hielo
hielo
Flag of Wallis and Futuna image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks for this solution and your explanation.  I'm positive you save me hours of frustration on this : )
Works great.  Thanks!  :)
Hi Hielo,

It looks like sometimes the url can look like this:
http://www.google.com/search?sourceid=navclient&aq=t&ie=UTF-8&rlz=1T4GGLR_enUS250US250&q=marrige+problems

Notice the 'aq' parameter which comes before the 'q' parameter.  Is there a way to change the regex to require that the character before the 'q' be either a '&' or '?'?

Thanks!
John