php正则表达式不同网页编码匹配中文汉字

| | Comments (6)



/^[\x{4e00}-\x{9fa5}]+$/u
匹配中文汉字的正则表达式困扰了很多网页编写者,而且在utf-8编码和gbk编码下写法是不一样的. 最近也在看这个,找到了正确的资料,贴出来和大家分享.

$str = "singlepoint单点日志";
if (preg_match("/^[\x{4e00}-\x{9fa5}]+$/u",$str)) {
print("该字符串全部是中文");
} else {
print("该字符串不全部是中文");
} 

下面的例子包含gbk,gb2312的用法,需要的可以取消gbk那行的注释,然后把utf-8的注释掉

<?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="?action=sub">
输入字符(数字,字母,汉字,下划线):
    <input type="text" name="dir" value="">
    <input type="submit" value="提交">
</form> 

6 Comments

php我还没有学过,编程学的都忘记了!

真捣鼓PHP呢。
学习学习。

php正则表达式。。这要向博客学习学习 教教 呵呵 我还不是很会呢

正责表达式不难,只有用的多才会熟悉,不用记住特殊符号,只要写的时候知道怎么查到资料就可以了.在google中搜索正责表达式,排在第一的就是一个教程,再下载一个辅助软件,就可以轻松学习了,摸索下就可以,花足够的时间就能学会.

正则表达式30分钟入门教程

http://unibetter.com/deerchao/zhengzhe-biaodashi-jiaocheng-se.htm

正则表达式的确是个很有用的东西

Leave a comment

Archives

Ads by google

Pages

Powered by Movable Type 4.24-en

About this Entry

This page contains a single entry by 单点日志 published on November 23, 2009 1:19 PM.

早产儿像袋鼠一样喂养新时代新观念 was the previous entry in this blog.

罗杰·费德勒(Roger Federer)提前锁定ATP年终第一 is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.