很多人可能已经写过并遇到了这个报错:
Warning: preg_match_all(): Compilation failed: PCRE does not support \L, \l, \N{name}, \U, or \u at offset 2
那么,我们要怎么解决呢?
很简单,就是这样:
/[\x{4e00}-\x{9fa5}]+/u
因此,想要利用php匹配中文,有两种写法:
/[\x7f-\xff]+/和/[\x{4e00}-\x{9fa5}]+/u
下面是一段测试代码,有兴趣的朋友可以看看运行结果:
<?php//临时启用全局错误提示ini_set('display_errors', true);error_reporting(E_ALL);$linkeBreak = (PHP_SAPI == 'cli') ? "\n" : '<br>';$str = '中文汉字English';$patternArr = array('/[\u4e00-\u9fa5]+/','/[\x{4e00}-\x{9fa5}]+/u','/[\x7f-\xff]+/',);foreach($patternArr as $pattern) {echo "Pattern: {$pattern} {$linkeBreak}";var_dump(testRegexpMatch($pattern, $str));echo $linkeBreak;}/*** 测试正则匹配* @param string $pattern 正则表达式* @param string $string 源字符串* @return array*/function testRegexpMatch($pattern, $string) {try {preg_match_all($pattern, $string, $matches);} catch (Exception $e) {return array('stauts' => false,'msg' => $e->getMessage(),'matches' => array(),);}return array('stauts' => true,'msg' => 'Success','matches' => $matches,);}
演示地址:PHP正则表达式匹配中文
源码下载:PHP正则表达式匹配中文演示源码
更多关于正则表达式入门的内容,请参考本站博客《我眼里的正则表达式入门教程》
更多关于正则表达式高级的内容,请参考本站博客《深入讲解正则表达式高级教程》
Windows正则表达式测试工具请从《正则表达式测试工具RegexBuddy-4.1.0》下载
Mac正则表达式测试工具请从《Mac正则表达式测试工具》下载
未经同意禁止转载!
转载请附带本文原文地址:正则表达式如何匹配中文,首发自 Zjmainstay学习笔记




