Myleft个人家园

 

 

搜索

preg_match 匹配中文出现错误bug的解决办法

已有 67 次阅读 2010-3-10 13:48 |个人分类:PHP|关键词:match preg bug 中文 办法

论坛上的一个网友提出的问题,在ascii编码的php文件中,定义的一个函数,简单描述如下:

    $censoww=array('婊');
    preg_match('/' . implode('|', $censoww) . '/i', $subject, $matches) ) { echo '非法内容';}

这是一个简单的禁字检测程序,广泛应用在bbs等程序中.可是这里出现了个问题,但$subject='存活' 或者 '存货'等时,这个程序竟然也提示非法内容。首先我提倡在程序中统一使用utf-8编码,当然这个程序在utf-8编码下应该没有问题的,可是在 ascii下,就会有一些奇怪的bug。这位网页的程序都是基于gbk的,不可能全部转码,只能打打补丁了,下面是简单的解决方案:

    mb_internal_encoding('gbk');//指定网络编码为gbk,这同时也作为正则匹配的编码
    $censoww=array('婊');
    //这里使用mb_eregi 代替preg_match,mb_eregi本身支持多字节的正则匹配
    if(mb_eregi( implode('|', $censoww) , $subject,$matches) ) { echo '非法内容';}

顺便翻译了下手册中关于这个函数的简单说明

    mb_eregi() executes the regular expression match with multibyte support, and returns 1 if matches are found. This function ignore case. If the optional third parameter was specified, the function returns the byte length of matched part, and the array regs will contain the substring of matched string.
    mb_eregi(),支持忽略大小写的多字节正则匹配,如果匹配成功,返回1,如果指定第三个可选参数,函数就返回匹配部分字节数,同时把所有匹配到的子串放在第三个参数指定的数组变量中

路过

雷人

握手

鲜花

鸡蛋

漂亮

评论 (0 个评论)

facelist

你需要登录后才可以评论 登录 | 注册
验证码 换一个

御舟工作室.

GMT+8, 2010-9-10 08:29 , Processed in 0.018419 second(s), 16 queries .

Powered by Discuz! X1.5RC

© 2001-2010 Comsenz Inc.