Reputation: 31
I looked around for a while, but probably I can't "Google" with the proper keywords, so I'm asking here. I need to extract the url from a string, using regexp (php)
A simple example should be helpful:
Target: extract the url http://en.wikipedia.org/wiki/Kettle
Base string:
/url?q=http://en.wikipedia.org/wiki/Kettle&sa=U&ei=VpnIUP22Js3B0gWKhoCgCQ&ved=0CB0QFjAA&usg=AFQjCNGS7-bieZB8Vh7xR5sjOy-KT86ANQ
Upvotes: 1
Views: 103
Reputation: 665
Test this regex: /q=([^&]+)/i
<?php
$url = '/url?q=http://en.wikipedia.org/wiki/Kettle&sa=U&ei=VpnIUP22Js3B0gWKhoCgCQ&ved=0CB0QFjAA&usg=AFQjCNGS7-bieZB8Vh7xR5sjOy-KT86ANQ';
$pattern = '/q=([^&]+)/i';
preg_match($pattern, $url, $res);
echo $res[1];
?>
Upvotes: 0
Reputation: 44259
There are better options than regex to do this. For instance, PHP provides the two functions parse_url
and parse_str
which do exactly what you want:
$query = parse_url($string, PHP_URL_QUERY);
parse_str($query, $parameters);
$result = $parameters['q'];
That is, of course, only unless you need to use regular expressions, because that is all your framework provides or because it's some kind of exercise.
Upvotes: 4