php urlencode函数用法教程

发布时间:2020-08-05编辑:脚本学堂
本文介绍了php urlencode函数的用法,针对网页url中的中文字符的一种编码转化方式,生成经过 encode过的网页url,感兴趣的朋友参考下。

理解urlencode:
urlencode:是指针对网页url中的中文字符的一种编码转化方式,最常见的就是baidu、google等搜索引擎中输入中文查询时候,生成经过 encode过的网页url。urlencode的方式一般有两种一种是传统的基于gb2312的encode(baidu、yisou等使用),一种是 基于utf-8的encode(google,yahoo等使用)。本工具分别实现两种方式的encode与decode。

例如,对“中文”进行url编码后的结果:
中文 -> GB2312的Encode -> %D6%D0%CE%C4
中文 -> UTF-8的Encode -> %E4%B8%AD%E6%96%87

html中的urlencode:
编码为GB2312的html文件中,
http://www.jb200.com/中文.rar -> 浏览器自动转换为 -> http://www.jb200.com/%D6%D0%CE%C4.rar
注意:Firefox对GB2312的Encode的中文URL支持不好,因为它默认是UTF-8编码发送URL的,但是ftp://协议可以,我试过了.我认为这应该算是Firefox一个bug.

编码为UTF-8的html文件中,
http://www.jb200.com/中文.rar -> 浏览器自动转换为 -> http://www.jb200.com/%E4%B8%AD%E6%96%87.rar

php中的urlencode:
 

<?php 
//GB2312的Encode 
echo urlencode("中文-_. ")."n"; //%D6%D0%CE%C4-_.+ 
echo urldecode("%D6%D0%CE%C4-_. ")."n"; //中文-_. 
echo rawurlencode("中文-_. ")."n"; //%D6%D0%CE%C4-_.%20 
echo rawurldecode("%D6%D0%CE%C4-_. ")."n"; //中文-_. 
?> 

除了 -_. 之外的所有非字母数字字符都将被替换成百分号(%)后跟两位十六进制数。
urlencode和rawurlencode的区别:
urlencode 将空格则编码为加号(+)
rawurlencode 将空格则编码为加号(%20)

如果要使用UTF-8的Encode,有两种方法:
一、将文件存为UTF-8文件,直接使用urlencode、rawurlencode即可。
二、使用mb_convert_encoding函数。
 

<?php 
$url = 'http://www.jb200.com/中文.rar'; 
echo urlencode(mb_convert_encoding($url, 'utf-8', 'gb2312'))."n"; 
echo rawurlencode(mb_convert_encoding($url, 'utf-8', 'gb2312'))."n"; 
//http%3A%2F%2Fwww.jb200.com%2F%E4%B8%AD%E6%96%87.rar 
?> 

实例:
 

<?php 
function parseurl($url="") 

$url = rawurlencode(mb_convert_encoding($url, 'gb2312', 'utf-8')); 
$a = array("%3A", "%2F", "%40"); 
$b = array(":", "/", "@"); 
$url = str_replace($a, $b, $url); 
return $url; 

$url="ftp://ud03:password@www.jb200.com/中文/中文.rar"; 
echo parseurl($url); 
//ftp://ud03:password@www.jb200.com/%D6%D0%CE%C4/%D6%D0%CE%C4.rar 
?> 

javascript中的URLEncode:
%E4%B8%AD%E6%96%87-_.%20%E4%B8%AD%E6%96%87-_.%20
encodeURI 不对下列字符进行编码:“:”、“/”、“;”、“?”、“@”等特殊字符

http://www.jb200.com/%E4%B8%AD%E6%96%87.rarhttp%3A%2F%2Fwww.jb200.com%2F%E4%B8%AD%E6%96%87.

完整函数:
 

function parseurl($url="",$input_charset,$output_charset)   
{   
$url = rawurlencode(mb_convert_encoding($url, $input_charset, $output_charset));   
$entities = array('%21', '%2A', '%27', '%28', '%29', '%3B', '%3A', '%40', '%26', '%3D', '%2B', '%24', '%2C', '%2F', '%3F', '%25', '%23', '%5B', '%5D'); 
$replacements = array('!', '*', "'", "(", ")", ";", ":", "@", "&", "=", "+", "$", ",", "/", "?", "%", "#", "[", "]"); 
$url = str_replace($entities, $replacements, $url);   
return $url;   
}