当前位置:K88软件开发文章中心编程语言PHPPHP01 → 文章内容

php和js判断字符串中是否包含汉字的正则表达式

减小字体 增大字体 作者:qiftwxf     来源:asp编程网  发布时间:2018-12-30 6:11:08

javascript的使用方法
<script>
var str = "asp编程网";
if (/^[\u4e00-\u9fa5]+$/.test(str)) 

alert("该字符串全是中文"); 
}  
else{ 
alert("该字符串包含非中文字符");
}
</script>

php的使用方法
php判断字符串中是否包含汉字,需要根据页面编码来判断,不同的编码,PHP的写法不一样
GBK编码的写法:
<?php
$str = "asp编程网";
if (preg_match("/^[\x80-\xff]+$/",$str)) {
    print("该字符串全是中文");
} else {
    print("该字符串包含非中文字符");
}
?>
utf8编码的写法:
<?php
$str = "asp编程网";
$str= iconv('GBK','UTF-8',$str);  //先将gbk编码转成utf-8编码
if (preg_match("/^[\x{4e00}-\x{9fa5}]+$/u",$str)) {
    print("该字符串全是中文");
} else {
    print("该字符串包含非中文字符");
}
?>

php和js判断字符串中是否包含汉字的正则表达式