抓取數據遇到 \u65b0\u6d6a\u5fae\u535a 等 Unicode 轉義序列,需還原為中文。本文提供兩種方案並重點分析 JSON 方案的單引號限制。
function replace_unicode_escape_sequence($match) {
return mb_convert_encoding(pack('H*', $match[1]), 'UTF-8', 'UCS-2BE');
}
$name = '\u65b0\u6d6a\u5fae\u535a';
$str = preg_replace_callback('/\\\\u([0-9a-f]{4})/i', 'replace_unicode_escape_sequence', $name);
echo $str; // 新浪微博
class Helper_Tool {
static function unicodeDecode($data) {
return preg_replace_callback(
'/\\\\u([0-9a-f]{4})/i',
function ($match) {
return mb_convert_encoding(pack('H*', $match[1]), 'UTF-8', 'UCS-2BE');
},
$data
);
}
}
$name = '\u65b0\u6d6a\u5fae\u535a';
$data = Helper_Tool::unicodeDecode($name); // 新浪微博
function unicodeDecode($name) {
$json = '{"str":"'.$name.'"}';
$arr = json_decode($json, true);
if (empty($arr)) return '';
return $arr['str'];
}
$name = '\u65b0\u6d6a\u5fae\u535a';
echo unicodeDecode($name); // 新浪微博
輸入字符串 絕不能包含單引號 ('),否則構造的 JSON 字符串語法無效,
json_decode返回 null。使用前必須預處理:$name = str_replace("'", "\'", $name); // 轉義單引號
pack('H*') 轉二進制,mb_convert_encoding 從 UCS-2BE 轉 UTF-8生產環境優先方案 A,無特殊字符限制、穩健可靠;可控輸入且極度追求性能時可用方案 B(需嚴格預處理)。