素晴らしいコードを発見したのでペタリ。
// 文字列のユニコードデコードを行う
function unicode_decode($str) {
return preg_replace_callback("/((?:[^\x09\x0A\x0D\x20-\x7E]{3})+)/", "decode_callback", $str);
}
function decode_callback($matches) {
$char = mb_convert_encoding($matches[1], "UTF-16", "UTF-8");
$escaped = "";
for ($i = 0, $l = strlen($char); $i < $l; $i += 2) {
$escaped .= "\u" . sprintf("%02x%02x", ord($char[$i]), ord($char[$i+1]));
}
return $escaped;
}
// 文字列のユニコードエンコードを行う
function unicode_encode($str) {
return preg_replace_callback("/\\\\u([0-9a-zA-Z]{4})/", "encode_callback", $str);
}
function encode_callback($matches) {
$char = mb_convert_encoding(pack("H*", $matches[1]), "UTF-8", "UTF-16");
return $char;
}
※英数字、及び記号はエスケープされないので注意されたし。
そしてこれ、PHP6からはネイティブで実装されるらしい。いやPHP5で追加してくれよ。