search
Homephp教程php手册php中正则匹配中文汉字

php中正则匹配中文汉字

Jun 13, 2016 am 10:15 AM
phpChinesematchexiststringusregularChinese characterKnowObtainneedpage

在php中如果你想正则来获取字符串中汉字我们先需要知道页面编码,正则匹配中文汉字根据页面编码不同而略有区别:GBK/GB2312编码:[x80-xff>]+ 或 [xa1-xff]+ 而UTF-8编码:[x{4e00}-x{9fa5}]+/u 。

 代码如下 复制代码

echo (mb_eregi("[x80-xff].","中d文") ? "有" : "无") ."汉字";
echo (mb_eregi("^([x80-xff].)+$","中文") ? "全是汉字" : ""); 看一判断全中文字符串函数

以下以PHP为例进行匹配:

 代码如下 复制代码

   $str = "学习php是一件快乐的事。";
   preg_match_all("/[x80-xff]+/", $str, $match);
   //UTF-8 使用:
   //preg_match_all("/[x{4e00}-x{9fa5}]+/u", $str, $match);
   print_r($match);
?>

输出:

Array
(
    [0] => Array
        (
            [0] => 学习
            [1] => 是一件快乐的事。
        )

)

正则汉字

 代码如下 复制代码

$str = "请问php中的eregi如何匹配汉字";
if (preg_match("/^[".chr(0x80)."-".chr(0xff)."]+$/",$str)) {
   echo "这是一个纯中文字符串";
} else{
   echo "这不是一个纯中文字串";
}
preg_match_all($pat,……)与preg_replace($pat,……)……


preg_match_all("/(汉字)+/ism","我是汉字,看你把我怎么着!",$m_a);
了各个编码的高位与低位的开始与结束,那么自然就可以写出正则,而且直接是十六位的,有啥困难?呵呵。不过要注意,在php里面,表示十六位是用的x


我们还可以用该正则表达式来判断是否是gb2312的汉字

 代码如下 复制代码

$str = "小小子";
if(preg_match("/^[xb0-xf7][xa0-xfe]+$/",$str)){
print($str."确实全是汉字");
} else {
print($str."这个真tc不全是汉字");
}
?>

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools