Reputation: 3158
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?
Upvotes: 3
Views: 11660
Reputation: 46728
@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);
Upvotes: 10
Reputation: 15905
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'];
Upvotes: 14