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

时间:2022-01-26 07:10:56

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= 123andrandom =abc,它可以是任何东西。我需要提取某个查询参数的值,在本例中是“test”(值123)。有办法吗?

3 个解决方案

#1


43  

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解析查询。

#2


2  

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

#3


0  

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

#1


43  

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解析查询。

#2


2  

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

#3


0  

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