简体   繁体   English

如何从PHP中的URL字符串提取查询参数?

[英]How do I extract query parameters from a URL string in PHP?

Users can input URLs using a HTML form on my website, so they might enter something like this: http://www.example.com?test=123&random=abc , it can be anything. 用户可以在我的网站上使用HTML表单输入URL,因此他们可以输入以下内容: http : //www.example.com?test=123&random=abc ,可以是任何内容。 I need to extract the value of a certain query parameter, in this case 'test' (the value 123). 我需要提取某个查询参数的值,在本例中为“ test”(值123)。 Is there a way to do this? 有没有办法做到这一点?

You can use parse_url and parse_str like this: 您可以像这样使用parse_urlparse_str

$query = parse_url('http://www.example.com?test=123&random=abc', PHP_URL_QUERY);
parse_str($query, $params);
$test = $params['test'];

parse_url allows to split an URL in different parts (scheme, host, path, query, etc); parse_url允许将URL拆分为不同的部分(方案,主机,路径,查询等); here we use it to get only the query ( test=123&random=abc ). 在这里,我们使用它仅获取查询( test=123&random=abc )。 Then we can parse the query with parse_str . 然后,我们可以使用parse_str解析查询。

I needed to check an url that was relative for our system so I couldn't use parse_str. 我需要检查一个相对于我们系统相对的url,所以我不能使用parse_str。 For anyone who needs it: 对于任何需要它的人:

$urlParts = null;
preg_match_all("~[\?&]([^&]+)=([^&]+)~", $url, $urlParts);

the hostname is optional but is required at least the question mark at the begin of parameter string: 主机名是可选的,但至少在参数字符串开头必须是问号:

$inputString = '?test=123&random=abc&usersList[]=1&usersList[]=2' ;

parse_str ( parse_url ( $inputString , PHP_URL_QUERY ) , $params );

print_r ( $params );

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

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