3
http://www.example.com?id=05

or

http://www.example.com?id=05&name=johnny

This is a string. And I want to get the value of $id from it.

What is the correct pattern for it?

dialogik
9,58218 gold badges78 silver badges122 bronze badges
asked Jul 29, 2012 at 5:41
3
  • Do you have information on what will be in the id param? All numbers? Commented Jul 29, 2012 at 5:44
  • Why use preg_match when you can use $params = parse_str(parse_url($url, PHP_URL_QUERY)) instead? Does your solution require only to use preg_match? That way you could just check $params['id'] for your value? Commented Jul 29, 2012 at 5:46
  • If you do want to figure out how to get the value of ID using regex, just as an exercise, it would help to tell us what you've tried so far and what part you're having trouble with. Commented Jul 29, 2012 at 6:09

2 Answers 2

14

You don't need regex (and you shouldn't be jumping straight to regex in the future unless you have a good reason).

Use parse_url() with PHP_URL_QUERY, which retrieves the querystring. Then pair this with parse_str().

$querystring = parse_url('http://www.mysite.com?id=05&name=johnny', PHP_URL_QUERY);
parse_str($querystring, $vars);
echo $var['id'];
answered Jul 29, 2012 at 5:44

4 Comments

Exactly what I was thinking. Just refreshed and saw your answer +1.
I have no reason actually, it's just for learning purposes, I guess I made a mistake on not mentioning it.
@user1091856 There are situations when it is appropriate, but in general you should first look for an internal (PHP provided) way, then see if it can be achieved with string manipulation (probably using explode()), and then try regular expressions.
Agreed. Regular expressions can do almost anything, but they often do it in a clumsy and complicated way. It's almost always harder than it seems to make sure that your regular expression won't break on an unexpected input.
10

@PhpMyCoder's solution is perfect. But if you absolutely need to use preg_match (though completely unnecessary in this case)

$subject = "http://www.mysite.com?id=05&name=johnny";
$pattern = '/id=[0-9A-Za-z]*/'; //$pattern = '/id=[0-9]*/'; if it is only numeric.
preg_match($pattern, $subject, $matches);
print_r($matches);
answered Jul 29, 2012 at 5:43

2 Comments

+1 for feeding my ego :P and answering with what was asked for
personally would have gave the check to PhpMyCoder

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.