php urlencode 实现
URL编码的基本概念
URL编码(Percent-Encoding)是将URL中的特殊字符转换为%后跟两位十六进制数的形式。PHP中可通过urlencode()函数实现,适用于查询字符串或路径部分。
使用urlencode()函数
urlencode()对字符串编码,替换空格为+,其他非字母数字字符为%XX格式:
$string = "Hello World! 123";
$encoded = urlencode($string);
echo $encoded; // 输出:Hello+World%21+123
使用rawurlencode()函数
rawurlencode()遵循RFC 3986标准,空格编码为%20而非+:
$string = "Hello World! 123";
$encoded = rawurlencode($string);
echo $encoded; // 输出:Hello%20World%21%20123
编码查询参数
构建URL查询字符串时,通常对参数值单独编码:
$params = [
'name' => 'John Doe',
'email' => 'john@example.com'
];
$query = http_build_query($params);
// 输出:name=John+Doe&email=john%40example.com
解码URL编码
使用urldecode()或rawurldecode()还原编码后的字符串:

$encoded = "Hello%20World%21";
$decoded = rawurldecode($encoded);
echo $decoded; // 输出:Hello World!
注意事项
- 路径部分推荐使用
rawurlencode(),查询部分可用urlencode()。 - 编码前避免重复编码,解码时需匹配原始编码方式。






