简体   繁体   English

PHP:使用preg_match获取url变量?

[英]PHP: Getting url variable with preg_match?

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. 我想从中获取$id的值。

What is the correct pattern for it? 它的正确模式是什么?

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. parse_url()PHP_URL_QUERY一起PHP_URL_QUERY ,它会检索查询字符串。 Then pair this with parse_str() . 然后将其与parse_str()配对。

$querystring = parse_url('http://www.mysite.com?id=05&name=johnny', PHP_URL_QUERY);
parse_str($querystring, $vars);

echo $var['id'];

@PhpMyCoder's solution is perfect. @ PhpMyCoder的解决方案非常完美。 But if you absolutely need to use preg_match (though completely unnecessary in this case) 但是如果你绝对需要使用preg_match(虽然在这种情况下完全没必要)

$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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM