PHP:URLをUTF-8にエンコードしたりデコードする方法

URLを、

http%3a%2f%2fhogehogetantan%2ecom%2f%e3%81%82%e3%81%84
%e3%81%86%e3%81%88%e3%81%8a%2ephp

みたいなよく見かけるコードにエンコードする方法です。
下はUTF-8の場合ですが、Shift-JISの場合は「UTF-8」の部分を「Shift-JIS」にすればおk。

<?php
$url='http://hogehogetantan.com/あいうえお.php';//元のURL
$result=urlencode(mb_convert_encoding($url, 'UTF-8', 'auto'));//UTFにしてからurlエンコード
print $result;
?>

これを元に戻すには、

<?php
$url=urldecode($result);
print $url;
?>

べつにURLに限らず使えます。
 



投稿日時:

コメントを残す

メールアドレスが公開されることはありません。


*

次のHTML タグと属性が使えます: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>