Skip to content

Instantly share code, notes, and snippets.

@huzemin
Created February 12, 2018 09:12
Show Gist options
  • Save huzemin/ae89289c9e8c389f0d94361e665c6f5a to your computer and use it in GitHub Desktop.
Save huzemin/ae89289c9e8c389f0d94361e665c6f5a to your computer and use it in GitHub Desktop.
正则表达式匹配中文字符

PHP 匹配中文字符

正则匹配中文汉字根据页面编码不同而略有区别

  1. GBK/GB2312编码:[x80-xff]+ 或 [xa1-xff]+
  2. UTF-8编码:[x{4e00}-x{9fa5}]+/u
// 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汉字字母数字下划线正则表达式
$str = '中文';
if(preg_match('#[\x{4e00}-\x{9fa5}]#', $str) {
  echo '中文';
} else {
  echo '不是中文';
}

Javascript 匹配中文

var str = "php编程";
if (/^[\u4e00-\u9fa5]+$/.test(str)) {
  alert("该字符串全部是中文");
} else {
  alert("该字符串不全部是中文");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment