php urlencode()

來源:互聯網
上載者:User

在PHP中有urlencode()、urldecode()、rawurlencode()、rawurldecode()這些函數來解決網頁
URL編碼解碼問題。

在ASP的時候URL編碼解碼很是惱火,Server.urlencode不太好用,遇到utf-8編碼的地址更是麻
煩。你要擷取百度、Google點擊到網站的網址連結中的關鍵字,要寫上一堆自訂函數來得到urldecode的效果。

摘錄一篇關於
PHP urlencode()函數的文章,對PHP處理URL作全面瞭解,文章來自373ren排行13,感謝。

理解
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.fufuok.com

/中文.rar -> 瀏覽器自動轉換為 -> http://www.fufuok.com/%D6%D0%CE%C4.rar

意:Firefox對GB2312的Encode的中文URL支援不好,因為它預設是utf-8編碼發送URL的,但是ftp://協議可以,應該算是
Firefox一個bug。

編碼為utf-8的html檔案中:

http://www.fufuok.com

/中文.rar -> 瀏覽器自動轉換為 ->

http://www.fufuok.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.fufuok.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.fufuok.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://fufu:password@www.fufuok.com
/中文/中文.rar";
echo parseurl($url);
//ftp://fufu:password@www.fufuok.com/%D6%D0%CE%C4/%D6%D0%CE%C4.rar
?>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.