Php: Select part of a url

Associate
Joined
5 Feb 2006
Posts
129
Location
Birmingham
Hi i have a script that extracts a url from a website by matching a pattern i now want to extract infomation from the url:

http://site.com/qaz/qaz?=qwerty

I basically want to capture the word after the =

so in this case qwerty

I have not a clue how to do this could anyone tell me what i should be looking at.

Thanks
 
Code:
// Made-up URL here!
$url = 'http://foo.bar/?foo=bar&baz=lol';

// Get the query string:
$query_string = substr($url, strpos($url, '?'));

// Parse the string into separate variables:
parse_str($query_string, $results);

// Results are now in the $results array. For example:
echo $results['foo']; // prints "bar"
echo $results['baz']; // prints "lol"
 
robmiller i couldn't get it to work so i run the exact code you posted, it dosent find the foo=bar result only the baz=lol do you know why?

Cheers
 
Instead of using substr(), you can use the purpose-built parse_url():

For the code above:
Code:
// Get the query string:
$url_parsed = parse_url($url);

// Parse the string into separate variables:
parse_str($url_parsed['query'], $results);
Should give the same result. While I expect using substr() would be faster, if you want to manipulate any other part of the URL later on then go with parse_url() instead since it levaes you with an array of component parts.
 
Back
Top Bottom