URLEncode
urlencode函数将传入的字符串参数进行URL编码。其返回的字符串中除了“ˉ—.”之外,所有非字母数字字符都被替换成百分号(%)后跟两位十六进制数,空格则编码为加号(+)。此函数便于将字符串编码并将其用于URL的请求部分,同时还便于将变量传递给下一页。
URLEncode:是指针对网页url中的中文字符的一种编码转化方式,最常见的就是Baidu、Google等搜索引擎中输入中文查询时候,生成经过 Encode过的网页URL。URLEncode的方式一般有两种一种是传统的基于GB2312的Encode(Baidu、Yisou等使用),一种是 基于UTF-8的Encode(Google,Yahoo等使用)。本工具分别实现两种方式的Encode与Decode。
中文 -> GB2312的Encode -> %D6%D0%CE%C4
中文 -> UTF-8的Encode -> %E4%B8%AD%E6%96%87
Html中的URLEncode
编码为GB2312的html文件中,http://www.nowamagic.net/中文.rar -> 浏览器自动转换为 -> http://www.nowamagic.net/%D6%D0%CE%C4.rar
注意:Firefox对GB2312的Encode的中文URL支持不好,因为它默认是UTF-8编码发送URL的,但是ftp://协议可以。
编码为UTF-8的html文件中,http://www.nowamagic.net/中文.rar -> 浏览器自动转换为 -> http://www.nowamagic.net/%E4%B8%AD%E6%96%87.rar
PHP中的URLEncode:
1
<?php
2
//GB2312的Encode
3
echo urlencode("中文-_. ")."
"; //%D6%D0%CE%C4-_.+
4
echo urldecode("%D6%D0%CE%C4-_. ")."
"; //中文-_.
5
echo rawurlencode("中文-_. ")."
"; //%D6%D0%CE%C4-_.%20
6
echo rawurldecode("%D6%D0%CE%C4-_. ")."
"; //中文-_.
7
?>
除了 -_. 之外的所有非字母数字字符都将被替换成百分号(%)后跟两位十六进制数。
urlencode和rawurlencode的区别:
urlencode 将空格则编码为加号(+)
rawurlencode 将空格则编码为加号(%20)
如果要使用UTF-8的Encode,有两种方法:
将文件存为UTF-8文件,直接使用urlencode、rawurlencode即可。
使用mb_convert_encoding函数。
1
<?php
2
$url = 'http://www.nowamagic.net/中文.rar';
3
echo urlencode(mb_convert_encoding($url, 'utf-8', 'gb2312'))."
";
4
echo rawurlencode(mb_convert_encoding($url, 'utf-8', 'gb2312'))."
";
5
//http%3A%2F%2Fwww.nowamagic.net%2F%E4%B8%AD%E6%96%87.rar
6
?>
实例:
01
<?php
02
function parseurl($url="")
03
{
04
$url = rawurlencode(mb_convert_encoding($url, 'gb2312', 'utf-8'));
05
$a = array("%3A", "%2F", "%40");
06
$b = array(":", "/", "@");
07
$url = str_replace($a, $b, $url);
08
return $url;
09
}
10
$url="ftp://ud03:password@www.nowamagic.net/中文/中文.rar";
11
echo parseurl($url);
12
//ftp://ud03:password@www.nowamagic.net/%D6%D0%CE%C4/%D6%D0%CE%C4.rar
13
?>
JavaScript中的URLEncode: %E4%B8%AD%E6%96%87-_.%20%E4%B8%AD%E6%96%87-_.%20,encodeURI 不对下列字符进行编码:“:”、“/”、“;”、“?”、“@”等特殊字符。