萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 过滤非汉字字符:仅保留中文的正则与编码转换实战

核心思路

利用 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'); // 转回

替代方案:mb_ereg_replace

$onlyChinese = mb_ereg_replace('[^\x{4e00}-\x{9fff}]', '', $str, 'usr');

性能提示

  • 大文本处理建议分块,避免正则回溯过深。
  • 仅需判断“是否包含中文”用 preg_match 而非 preg_match_all。
  • 频繁调用可预编译正则或缓存结果。
copyright © 萬盛學電腦網 all rights reserved