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
2 Answers 2
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
Yzmir Ramirez
Exactly what I was thinking. Just refreshed and saw your answer +1.
user1091856
I have no reason actually, it's just for learning purposes, I guess I made a mistake on not mentioning it.
Bailey Parker
@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.octern
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.
@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
Bailey Parker
+1 for feeding my ego :P and answering with what was asked for
no1uknow
personally would have gave the check to PhpMyCoder
lang-php
$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?