You need to enable JavaScript to run this app. PHP如何解析URL并自动在对应位置添加合适的编码处理?
优惠活动
大模型
产品
解决方案
定价
更多

PHP如何解析URL并自动在对应位置添加合适的编码处理?

PHP实现URL解析与编码处理方案

提取查询字符串的键、值数组

通过parse_url()解析URL获取查询字段段,再用parse_str()将查询字符串转为关联数组,拆分即可得到目标的$key和$value数组。

编码拼接生成最终URL

按照要求对不同部分做对应编码处理后拼接即可,完整可运行代码如下:

// 替换为用户提交的实际URL
$url = 'http://example.com/autos/cars/list.php?country=usa&min_price=5000';

// 解析URL所有组成部分
$parsed_url = parse_url($url);

// 解析查询字符串为关联数组
$query_arr = [];
if (isset($parsed_url['query'])) {
    parse_str($parsed_url['query'], $query_arr);
}

// 第一步:生成$key和$value数组
$key = array_keys($query_arr);
$value = array_values($query_arr);

// 输出两个数组验证结果
print_r($key);
echo '<br>';
print_r($value);
echo '<br>';

// 第二步:拼接编码后的完整URL
// 组装?之前的基础URL部分,如需兼容带端口的URL可自行追加$parsed_url['port']判断
$base_url = $parsed_url['scheme'] . '://' . $parsed_url['host'] . $parsed_url['path'];
$encoded_base = rawurlencode($base_url);

// 处理查询参数部分
$encoded_query = [];
foreach ($query_arr as $k => $v) {
    $processed_v = is_numeric($v) ? intval($v) : urlencode($v);
    $encoded_query[] = $k . '=' . $processed_v;
}
$final_query = implode('&', $encoded_query);

// 拼接输出最终URL
$final_url = $encoded_base . '?' . $final_query;
echo $final_url;

示例运行输出:

  • $key数组:Array ( [0] => country [1] => min_price )
  • $value数组:Array ( [0] => usa [1] => 5000 )
  • 最终编码URL:http%3A%2F%2Fexample.com%2Fautos%2Fcars%2Flist.php?country=usa&min_price=5000

内容的提问来源于stack exchange,提问作者I Ali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 23:06:00