Home  >  Article  >  php教程  >  php 汉字正则表达式实例详解

php 汉字正则表达式实例详解

WBOY
WBOYOriginal
2016-06-08 17:23:131045browse

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

<script>ec(2);</script>


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("该字符串不全部是中文");
}
Statement:
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