利用 Unicode 中文范围 \u4e00-\u9fff(基本汉字区)配合 preg_match_all 的 /u 修饰符提取中文,再拼接。需注意编码一致性:源文件、正则、字符串均为 UTF-8。
<?php
$str = "a 1b 2b<中文>。xxyy字符";
// 确保内部编码 UTF-8
mb_internal_encoding('UTF-8');
// 提取中文
preg_match_all('/[\x{4e00}-\x{9fff}]+/u', $str, $matches);
$chinese = implode('', $matches[0]);
echo $chinese; // 输出:中文字符
// 扩展 A/B/C/D/E/F + 兼容扩展
$pattern = '/[\x{4e00}-\x{9fff}\x{3400}-\x{4dbf}\x{20000}-\x{2a6df}\x{2a700}-\x{2b73f}\x{2b740}-\x{2b81f}\x{2b820}-\x{2ceaf}]/u';
preg_match_all($pattern, $str, $m);
$all_cjk = implode('', $m[0]);
若源文件为 GBK,需先转 UTF-8 再匹配:
$str = mb_convert_encoding($str, 'UTF-8', 'GBK');
// ... 正则匹配 ...
$str = mb_convert_encoding($str, 'GBK', 'UTF-8'); // 转回
$onlyChinese = mb_ereg_replace('[^\x{4e00}-\x{9fff}]', '', $str, 'usr');
preg_match 而非 preg_match_all。