敏感词过滤及替换方法

php教程11年前 (2014-08-27)15140

敏感词过滤及替换方法

  1. /**

  2. * 将需要被和谐的词加入到lib/denywords.php文件中

  3. * 判断用户发布的产品是否合法

  4. * @param String $string 待检查的字符串

  5. * @param Array $denywords 危险的关键词

  6. * @param String $replace 是否进行替换

  7. * @param String $replace_word 替换的文字

  8. * @return true:合法 string:替代后的字符串或相应的非法词

  9. */

  10. function check_filter ( $string,$replace = true, $replace_word = '**' ) {

  11.         include_once 'denywords.php';

  12.         $deny      = '';                                 //一个需要被屏蔽的关键词

  13.         $res       = '';                                 //返回的被合谐的关键词

  14.         //将提交上来的非UTF-8转换成UTF-8的编码

  15.         if ( 'UTF-8' != mb_check_encoding( $string ) ) { $string = mb_convert_encoding( $string, 'UTF-8' );        }

  16.         if ( $replace === true ) {                       //对输入的词进行替换

  17.                 $string = str_ireplace( $denywords, $replace_word, $string );

  18.                 return $string;

  19.         } else {

  20.                 $string = preg_replace('/\s/','',$string); //不进行替换则全部检查,遇到第一个不合格的词则返回该词

  21.                 foreach ( $denywords as $deny ) {            //遍历和谐词表

  22.                         if ( stristr ( $string, $deny ) != false ) {

  23.                                 $res .= $deny . ',';

  24.                         }

  25.                 }

  26.                 if ( empty( $res ) ) {

  27.                         return false;                             //没有不合法的词

  28.                 } else{

  29.                         return $res;

  30.                 }

  31.         }

  32. }


敏感词过滤包

denywords.zip


标签: php

“敏感词过滤及替换方法” 的相关文章

发表评论

访客

看不清,换一张

◎欢迎参与讨论,请在这里发表您的看法和观点。