php正则匹配中文utf8编码

在javascript中,要判断字符串是中文是很简单的。比如:

var str = "php编程";
if (/^[\u4e00-\u9fa5]+$/.test(str)) {
alert("该字符串全部是中文");
} else {
alert("该字符串不全部是中文");
}

php部分:

<?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>";  
}
}
?>
本文出至: 新太潮流网络博客

猜你喜欢

转载自blog.csdn.net/weixin_42266757/article/details/80447337