Home  >  Article  >  php教程  >  php 正则判断中文(自动识别UTF-8 & GBK编码)

php 正则判断中文(自动识别UTF-8 & GBK编码)

WBOY
WBOYOriginal
2016-05-25 16:45:581190browse

下面这款实例程序是一款PHP 正确匹配UTF8或gbk中文的正则表达式程序,能准确的获取不同编码情况的中文汉字的识别.

PHP实例代码如下:

<?php
$action = trim($_get[&#39;action&#39;]);  
if($action == "sub")  
{  
    $str = $_post[&#39;dir&#39;];     
    //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汉字字母数字下划线正则表达式.


永久地址:

转载随意~请带上教程地址吧^^

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn