Reputation: 3296
I am trying to extract a portion of a URL using regex.
An example of my url would be:
http://www.google.com/search?sourceid=chrome&ie=UTF-8&q=food
Using php, how could I extract the data in the q variable or the sourceid variable?
Upvotes: 2
Views: 86
Reputation: 59699
Don't use a regex for this. Instead, use parse_url()
and parse_str()
.
$params = array();
$url= "http://www.google.com/search?sourceid=chrome&ie=UTF-8&q=food";
$url_query = parse_url($url, PHP_URL_QUERY);
parse_str($url_query, $params);
echo $params['q']; // Outputs food
Upvotes: 7
Reputation: 219794
A perfect tutorial for what you're trying to accomplish:
$parts = parse_url('http://www.google.com/search?sourceid=chrome&ie=UTF-8&q=food');
parse_str($parts['query'], $query);
echo $query['q'];
Upvotes: 1