php正则匹配汉字!
/^[x{4e00}-x{9fa5}]+$/u
用正则匹配,不同编码,不同程序语言,都会有不同,应该正确理解与应用,不然不仅得不到想要的结果,还会错误百出哦。
1、一个utf-8编码的例子:
<?php
$str = "汉字";
if (preg_match("/^[x{4e00}-x{9fa5}]+$/u",$str)) {
print("该字符串全部是中文");
} else {
print("该字符串不全部是中文");
}
//by http://www.jb200.com
?>
2、一个包含gbk,gb2312的例子:
<?php
$action = trim($_GET['action']);
if($action == "sub")
{
$str = $_POST['dir'];
//if(!preg_match("/^[".chr(0xa1)."-".chr(0xff)."A-Za-z0-9_]+$/",$str)) //GB2312汉字字母数字下划线正则表达式
if(!preg_match("/^[x{4e00}-x{9fa5}A-Za-z0-9_]+$/u",$str)) //UTF-8汉字字母数字下划线正则表达式
{
echo "<font color=red>您输入的[".$str."]含有违法字符</font>";
}
else
{
echo "<font color=green>您输入的[".$str."]完全合法,通过!</font>";
}
}
?>
<form method="POST" action="?action=sub">
输入字符(数字,字母,汉字,下划线):
<input type="text" name="dir" value="">
<input type="submit" value="提交">
</form>
建议大家亲自动手测试下,看看效果是怎么样的?php正则匹配英文比较简单,匹配汉字时请多加留心哦。