php 实现urlencode
使用 urlencode 函数
PHP 提供了内置的 urlencode 函数,用于对字符串进行 URL 编码。该函数会将字符串中的非字母数字字符转换为 % 后跟两位十六进制数的形式,空格会被转换为 +。
$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 查询字符串时,通常需要对参数名和参数值分别进行编码。
$params = [
'name' => 'John Doe',
'age' => 30,
'city' => 'New York'
];
$query = http_build_query($params);
echo $query; // 输出: name=John+Doe&age=30&city=New+York
编码整个 URL
如果需要编码整个 URL,可以使用 urlencode 或 rawurlencode 结合 parse_url 函数。
$url = "https://example.com/search?q=PHP URL encoding";
$parsed = parse_url($url);
$scheme = $parsed['scheme'];
$host = $parsed['host'];
$path = $parsed['path'];
$query = rawurlencode($parsed['query']);
$encodedUrl = "$scheme://$host$path?$query";
echo $encodedUrl; // 输出: https://example.com/search?q=PHP%20URL%20encoding
解码 URL
使用 urldecode 或 rawurldecode 函数可以解码 URL 编码的字符串。
$encoded = "Hello+World%21";
$decoded = urldecode($encoded);
echo $decoded; // 输出: Hello World!
$encoded = "Hello%20World%21";
$decoded = rawurldecode($encoded);
echo $decoded; // 输出: Hello World!
注意事项
urlencode和rawurlencode不会编码-,_,.等字符。- 在编码路径部分时,建议使用
rawurlencode以避免+被误解为空格。 - 在编码查询参数时,
http_build_query会自动处理编码问题。







