在PHP中有urlencode()、urldecode()、rawurlencode()、rawurldecode()這些函數來解決網頁URL編碼解碼問題。
理解urlencode:
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.phpernote.com/中文.rar -> 瀏覽器自動轉換為 -> http://www.phpernote.com/%D6%D0%CE%C4.rar
注意:Firefox對GB2312的Encode的中文URL支援不好,因為它預設是utf-8編碼發送URL的,但是ftp://協議可以,應該算是Firefox一個bug。
編碼為utf-8的html檔案中:
http://www.phpernote.com/中文.rar -> 瀏覽器自動轉換為 -> http://www.phpernote.com/%E4%B8%AD%E6%96%87.rar
PHP中的urlencode:
//GB2312的Encodeecho urlencode("中文-_. ")."\n"; //%D6%D0%CE%C4-_.+echo urldecode("%D6%D0%CE%C4-_. ")."\n"; //中文-_.echo rawurlencode("中文-_. ")."\n"; //%D6%D0%CE%C4-_.%20echo rawurldecode("%D6%D0%CE%C4-_. ")."\n"; //中文-_.
除了 -_. 之外的所有非字母數字字元都將被替換成百分比符號(%)後跟兩位十六進位數。
urlencode和rawurlencode的區別:
urlencode 將空格則編碼為加號(+)
rawurlencode 將空格則編碼為加號(%20)
我上個版本的txt檔案分割器(線上)代碼都是採用urlencode,從來沒有發現過這個問題,結果導致今天出了嚴重的bug,所有帶空格的url都無法解析了,導致分割好的檔案無法下載。使用rawurlencode()函數,解決了這個問題。
如果要使用utf-8的Encode,有兩種方法:
一、將檔案存為utf-8檔案,直接使用urlencode、rawurlencode即可。
二、使用mb_convert_encoding函數。
$url = 'http://www.phpernote.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.huikaiche.com%2F%E4%B8%AD%E6%96%87.rar
應用執行個體:
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://yongfu:password@www.huikaiche.com/中文/中文.rar";echo parseurl($url);//ftp://yongfu:password@www.huikaiche.com/%D6%D0%CE%C4/%D6%D0%CE%C4.rar
您可能感興趣的文章
- javascript的字串編碼函數escape,encodeURI,encodeURIComponent比較與分析
- php字串替換函數str_replace速度比preg_replace快
- PHP 產生連續的數字(字母)數組函數range()分析,PHP抽獎程式函數
- PHP中的字串處理函數(String Functions) 全總結
- php提取社會安全號碼碼中的生日日期以及驗證是否為未成年人的函數
- php在數組中尋找某個值是否存在(in_array(),array_search(),array_key_exists())
- 用PHP函數memory_get_usage擷取當前PHP記憶體消耗量以實現程式的效能最佳化
- 發送郵件SMTP Error Could not connect to SMTP host. send fail的解決辦法
http://www.bkjia.com/PHPjc/764188.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/764188.htmlTechArticle在PHP中有urlencode()、urldecode()、rawurlencode()、rawurldecode()這些函數來解決網頁URL編碼解碼問題。 理解urlencode: urlencode: 是指標對網頁url中的...