Home > php教程 > php手册 > body text

php正则表达式匹配中文

WBOY
Release: 2016-06-13 09:48:05
Original
1034 people have browsed it

在php中要利用正则来匹配中文汉字的话我们需要了解字符串编码然后还有汉字的内码这样才可以方便快速的实现精确的匹配中文汉字出来,下面我来给大家介绍介绍。


在php中来判断字符串是否为中文,就会沿袭这个思路:

 代码如下 复制代码
$str = "php编程";
if (preg_match("/^[u4e00-u9fa5]+$/",$str)) {
print("该字符串全部是中文");
} else {
print("该字符串不全部是中文");
}
?>

不过,很快就会发现,php并不支持这样的表达,报错:
Warning: preg_match() [function.preg-match]: Compilation failed: PCRE does not support L, l, N, U,

or u at offset 3 in test.php on line 3

刚开始从google上查了很多次,想从php正则表达式对于十六进制数据的

表达方式上进行突破,发现在php中,是用x表示十六进制数据的。于是,

变换成如下的代码:

 代码如下 复制代码
$str = "php编程";
if (preg_match("/^[x4e00-x9fa5]+$/",$str)) {
print("该字符串全部是中文");
} else {
print("该字符串不全部是中文");
}

貌似不报错了,判断的结果也正确,不过把$str换成“编程”两字,结果却还是显示“该字符串不全部是中文”,看

来这样的判断还是不够准确。


如果要精准匹配中文,即匹配纯中文字符,或匹配中文字符加上全角标点,则需要根据不同编码环境使用不同方法。

下面以两种常用的编码(gb2312,utf-8)

下面给两个例子:

 代码如下 复制代码

(1)     ANSI编程环境下:

$strtest = “yyg中文字符yyg”;

$pregstr = "/([".chr(0xb0)."-".chr(0xf7)."][".chr(0xa1)."-".chr(0xfe)."])+/i";

if(preg_match($pregstr,$strtest,$matchArray)){

echo $matchArray[0];

}

//output:中文字符

(2)     Utf-8编程环境下:

$strtest = “yyg中文字符yyg”;

$pregstr = "/[x{4e00}-x{9fa5}]+/u";

if(preg_match($pregstr,$strtest,$matchArray)){

echo $matchArray[0];

}

//output:中文字符

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!