如何从 PHP 中的 URL 字符串中提取查询参数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4784243/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I extract query parameters from a URL string in PHP?
提问by soren.qvist
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. I need to extract the value of a certain query parameter, in this case 'test' (the value 123). Is there a way to do this?
用户可以在我的网站上使用 HTML 表单输入 URL,因此他们可能会输入如下内容:http://www.example.com?test=123&random=abc,它可以是任何内容。我需要提取某个查询参数的值,在本例中为“test”(值 123)。有没有办法做到这一点?
回答by Arnaud Le Blanc
You can use parse_url
and parse_str
like this:
您可以使用parse_url
并parse_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); here we use it to get only the query (test=123&random=abc
). Then we can parse the query with parse_str
.
parse_url
允许将 URL 拆分为不同的部分(方案、主机、路径、查询等);在这里,我们使用它来仅获取查询 ( test=123&random=abc
)。然后我们可以解析查询parse_str
。
回答by Rob
I needed to check an url that was relative for our system so I couldn't use parse_str. For anyone who needs it:
我需要检查一个相对于我们系统的 url,所以我不能使用 parse_str。对于任何需要它的人:
$urlParts = null;
preg_match_all("~[\?&]([^&]+)=([^&]+)~", $url, $urlParts);
回答by Hugo Ferreira
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 );