php urlencode 实现
PHP 中 urlencode 的实现方法
在 PHP 中,urlencode 函数用于对字符串进行 URL 编码,确保字符串可以安全地传输。以下是几种实现方式:
使用 urlencode 函数
urlencode 是 PHP 内置函数,直接调用即可对字符串进行编码。它会将空格转换为 + 符号,其他非字母数字字符转换为 % 后跟两位十六进制数。

$string = "Hello World!";
$encoded = urlencode($string);
echo $encoded; // 输出:Hello+World%21
使用 rawurlencode 函数
rawurlencode 与 urlencode 类似,但会将空格编码为 %20 而不是 +,更符合 RFC 3986 标准。

$string = "Hello World!";
$encoded = rawurlencode($string);
echo $encoded; // 输出:Hello%20World%21
手动实现 URL 编码
如果需要手动实现 URL 编码,可以使用 bin2hex 和 str_split 结合的方式:
function manualUrlEncode($string) {
$encoded = '';
$length = strlen($string);
for ($i = 0; $i < $length; $i++) {
$char = $string[$i];
if (ctype_alnum($char) || $char == '-' || $char == '_' || $char == '.' || $char == '~') {
$encoded .= $char;
} else {
$encoded .= '%' . strtoupper(bin2hex($char));
}
}
return $encoded;
}
$string = "Hello World!";
$encoded = manualUrlEncode($string);
echo $encoded; // 输出:Hello%20World%21
处理数组或复杂数据
对于数组或复杂数据结构,可以结合 http_build_query 和 urlencode 实现编码:
$data = array(
'name' => 'John Doe',
'email' => 'john@example.com'
);
$query = http_build_query($data);
echo $query; // 输出:name=John+Doe&email=john%40example.com
注意事项
urlencode适用于查询参数,而rawurlencode更适合路径部分。- 编码后的字符串在解码时需使用
urldecode或rawurldecode。 - 特殊字符(如
&、=)在查询字符串中需额外处理。






