解析url信息
<?php
$url = 'https://www.php.net/manual/zh/language.types.php?name=Tom&age=23';
// 方式一:parse_url
print_r(parse_url($url));
// Array
// (
// [scheme] => https
// [host] => www.php.net
// [path] => /manual/zh/language.types.php
// [query] => name=Tom&age=23
// )
// 方式二:pathinfo
print_r(pathinfo($url));
// Array
// (
// [dirname] => https://www.php.net/manual/zh
// [basename] => language.types.php?name=Tom&age=23
// [extension] => php?name=Tom&age=23
// [filename] => language.types
// )
// 方式三:basename
print_r(basename($url));
// language.types.php?name=Tom&age=23
解析查询参数
<?php
/**
* 将字符串参数变为数组
* @param $query string
* @return array
* */
function decodeUrlQuery($query_str)
{
$query_pairs = explode('&', $query_str);
$params = [];
foreach ($query_pairs as $query_pair) {
$item = explode('=', $query_pair);
$params[$item[0]] = $item[1];
}
return $params;
}
/**
* 将参数变为字符串
* @param $query_array array
* @return string
*/
function encodeUrlQuery($query_array)
{
$tmp = array();
foreach ($query_array as $key => $value) {
$tmp[] = $key . '=' . $value;
}
return implode('&', $tmp);
}
// 示例
$url = 'https://www.php.net/manual/zh/language.types.php?name=Tom&age=23';
// 字符串转数组
$query_str = parse_url($url)['query'];
$query_array = decodeUrlQuery($query_str);
print_r($query_array);
// Array
// (
// [name] => Tom
// [age] => 23
// )
// 数组转字符串
print_r(encodeUrlQuery($query_array));
// name=Tom&age=23
扩展:查询字符串编码
使用php自带的查询参数编码函数
$data = [
'name' => 'Tom',
'age' => 23
];
echo encodeUrlQuery($data) . PHP_EOL;
// name=Tom&age=23
echo http_build_query($data) . PHP_EOL;
// name=Tom&age=23
如果是中文字符就会被编码
$data = [
'name' => '汤姆',
'age' => 23
];
echo encodeUrlQuery($data) . PHP_EOL;
// name=汤姆&age=23
echo http_build_query($data) . PHP_EOL;
// name=%E6%B1%A4%E5%A7%86&age=23