PHP 和 Python 一样提供了函数parse_url(string $url, int $component = -1)
,就很方便。
这个函数有两个参数:
url
:这个参数是要被解析的 URL(以 string 格式)。component
:使用PHP_URL_SCHEME
,PHP_URL_HOST
,PHP_URL_PORT
,PHP_URL_USER
,PHP_URL_PASS
,PHP_URL_PATH
,PHP_URL_QUERY
,PHP_URL_FRAGMENT
来指定输出的 URL 部分(除了PHP_URL_PORT
为 int 类型,其他均以 string 类型输出)。
如果不带component
,则该参数默认为-1
,将会输出一个数组。
举些例子帮助理解。假设 URL 为https://www.example.com/?keyword=abc&id=12
。代码如下:
<?php
$url="https://www.example.com/?keyword=abc&id=12";
//显示格式化之后的数组
var_dump(parse_url($url));
//输出格式化之后的数组的'query'对应的内容
echo parse_url($url)['query'];
//换行
echo '<br>';
//这里指定输出的内容为 host 部分
echo parse_url($url,PHP_URL_HOST);
?>
输出内容如下:
array(4) {
["scheme"]=>
string(5) "https"
["host"]=>
string(15) "www.example.com"
["path"]=>
string(1) "/"
["query"]=>
string(17) "keyword=abc&id=12"
}
keyword=abc&id=12
www.example.com
希望可以帮到有需要的人~