使い道がわからん
もうすぐ廃止になるJavaScriptのescape関数なのだが、例えばこんな風に文字列をescape関数に渡すと
<html> <head> <meta http-equiv="content-type" content="text/html;charset=utf-8" /> <script language="javascript"> function test(){ var str = document.getElementById('tibet').innerHTML; var esc = escape(str); alert(esc); } </script> </head> <body> <div id="tibet">ダライラマ</div> <button onClick="test();">test</button> </body> </html>
alertに表示されるのは「%u30C0%u30E9%u30A4%u30E9%u30DE」という書式になっている文字列で、ようするにescape関数は文字列を%uで始まるエスケープコード付きの文字列にする。
これをそのままPHPに渡してデコードするには、
<?php $str = '%u30C0%u30E9%u30A4%u30E9%u30DE'; $decode = preg_replace_callback("/(%u)([0-9a-zA-Z]+)/", '_decode', $str); function _decode($array){ return mb_convert_encoding(pack("H*", $array[2]), 'UTF-8', 'UCS-2'); } ?>
こんな感じで処理する。逆に、PHP側で文字列をJavaScriptのescape処理と同様に加工する場合は
<?php $str = 'ダライラマ'; preg_match_all("/(.)/u", $str, $matches); foreach($matches[1] as $k => $v){ $matches[1][$k] = '%u' . strtoupper(bin2hex(mb_convert_encoding($v, 'UCS-2', 'UTF-8'))); } $encode = implode("", $matches[1]); ?>
でできる。
と、ここまではいいのだが、JavaScriptでエスケープ処理された文字列をやり取りして面白いことができないか考えても、特に何も思いつかないので困った。
コメントを残す