1

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
2
  • 3
    Do you really need to use regex? Commented Dec 12, 2012 at 14:57
  • Just FYI, take a look at this tool: gskinner.com/RegExr Really helps testing regex expressions. Commented Dec 12, 2012 at 14:57

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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];
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.