Home > Backend Development > PHP Tutorial > 关于php正则匹配汉字的方法介绍_PHP

关于php正则匹配汉字的方法介绍_PHP

WBOY
Release: 2016-06-01 12:08:10
Original
879 people have browsed it

php正则匹配汉字!

/^[\x{4e00}-\x{9fa5}]+$/u

以上这个正则表达式就是困扰了很多php程序员的匹配汉字的正则表达式

大家可能会觉得很简单,实际上不同编码,不同程序语言,都有些细微的出入,稍不注意就得不到正确的结果。

下面是utf-8编码的例子:
$str = "汉字";<br>if (preg_match("/^[\x{4e00}-\x{9fa5}]+$/u",$str)) {<br>print("该字符串全部是中文");<br>} else {<br>print("该字符串不全部是中文");<br>} <br>

下面的例子包含gbk,gb2312的例子:

<?php <BR>$action = trim($_GET['action']);<br>if($action == "sub")<br>{<br>    $str = $_POST['dir'];    <br>    //if(!preg_match("/^[".chr(0xa1)."-".chr(0xff)."A-Za-z0-9_]+$/",$str)) //GB2312汉字字母数字下划线正则表达式 <br>    if(!preg_match("/^[\x{4e00}-\x{9fa5}A-Za-z0-9_]+$/u",$str))   //UTF-8汉字字母数字下划线正则表达式<br>    {   <br>         echo "<font color="red">您输入的[".$str."]含有违法字符</font>";   <br>     }<br>     else <br>     {<br>         echo "<font color="green">您输入的[".$str."]完全合法,通过!</font>";   <br>     }<br>}<br>?><br><form method="POST" action="?action=sub"> <br>输入字符(数字,字母,汉字,下划线):<br>     <input type="text" name="dir" value=""><br>     <input type="submit" value="提交"><br> </form>

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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template