php urlencode 实现
URL编码的基本概念
URL编码(Percent-Encoding)是将特殊字符转换为百分号(%)后跟两位十六进制数的形式。PHP中常用urlencode()函数实现,适用于查询字符串或URL参数编码。
使用 urlencode() 函数
urlencode() 对字符串编码,替换空格为+,非字母数字字符为%XX格式:
$string = "Hello World!@#";
$encoded = urlencode($string);
echo $encoded; // 输出:Hello+World%21%40%23
使用 rawurlencode() 函数
rawurlencode() 遵循RFC 3986标准,空格编码为%20而非+,更适合路径部分编码:
$string = "Hello World!@#";
$encoded = rawurlencode($string);
echo $encoded; // 输出:Hello%20World%21%40%23
编码URL查询参数
构建查询字符串时,仅对参数值编码,键通常无需编码:
$params = [
'name' => 'John Doe',
'email' => 'john@example.com'
];
$query = http_build_query($params);
echo $query; // 输出:name=John+Doe&email=john%40example.com
解码URL编码字符串
使用urldecode()或rawurldecode()还原编码后的字符串:
$encoded = "Hello%20World%21";
$decoded = rawurldecode($encoded);
echo $decoded; // 输出:Hello World!
注意事项
- 编码整个URL可能导致协议(
://)或主机名被错误编码,应仅对查询或路径部分处理。 http_build_query()自动处理数组参数,生成正确编码的查询字符串。







