background image

使用 PHP 正则判断中文编码(自动识别 utf-8 & gbk

编码)

下面这款实例程序是一款 php 正确匹配 utf8 或 gbk 中文的正则表达式程序,能准确的
获取不同编码情况的中文汉字的识别。
<?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=”">
输入字符(数字,字母,汉字,下划线):
    <input type=”text” name=”dir” value=”">
    <input type=”submit” value=”

提交 >

</form>
gbk: 
  preg_match(“/^[".chr(0xa1)."-".chr(0xff)."a-za-z0-9_] $/”,$str); //gb2312 汉 字
字母数字下划线正则表达式