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

php用正则表达式匹配中文实例详解

WBOY
Release: 2016-06-06 20:26:47
Original
1356 people have browsed it

php中怎么用正则表达式匹配中文,需要注意什么,本文就详解一下这个,还有实例

在php中汉字正则可能有些朋友觉得很简单,但是在使用时会发现在gbk编码与uft8编码可能会有点区别哦,下面小编来介绍一下。
gbk编码下汉字正则

1.判断字符串是否全是汉字

复制代码 代码如下:


    $str = '全部是汉字测试';
    if (preg_match_all("/^([x81-xfe][x40-xfe])+$/", $str, $match)) {
        echo '全部是汉字'; 
    } else {
        echo '不全是汉字';
    }
?>


当$str = '全部是汉字测试'; 时输出"全部是汉字";
当$str = 'all全部是汉字测试'; 时输出"不全是汉字";

2.判断字符串是否包含汉字

复制代码 代码如下:


    $str = '汉字3测试';
    if (preg_match("/([x81-xfe][x40-xfe])/", $str, $match)) {
        echo '含有汉字'; 
    } else {
        echo '不含有汉字';
    }
?>


当$str = '汉字3测试'; 时输出"含有汉字";
当$str = 'abc345'; 时输出"不含有汉字";
上述变量$str的内容与utf8还是gbk编码无关,判断结果是一样的。
utf-8编码下用正则表达式如何匹配汉字

复制代码 代码如下:


$str = "php编程";
if (preg_match("/^[x{4e00}-x{9fa5}]+$/u",$str)) {
print("该字符串全部是中文");
} else {
print("该字符串不全部是中文");

Related labels:
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!