敏感词过滤及替换方法
敏感词过滤及替换方法
/**
* 将需要被和谐的词加入到lib/denywords.php文件中
* 判断用户发布的产品是否合法
* @param String $string 待检查的字符串
* @param Array $denywords 危险的关键词
* @param String $replace 是否进行替换
* @param String $replace_word 替换的文字
* @return true:合法 string:替代后的字符串或相应的非法词
*/
function check_filter ( $string,$replace = true, $replace_word = '**' ) {
include_once 'denywords.php';
$deny = ''; //一个需要被屏蔽的关键词
$res = ''; //返回的被合谐的关键词
//将提交上来的非UTF-8转换成UTF-8的编码
if ( 'UTF-8' != mb_check_encoding( $string ) ) { $string = mb_convert_encoding( $string, 'UTF-8' ); }
if ( $replace === true ) { //对输入的词进行替换
$string = str_ireplace( $denywords, $replace_word, $string );
return $string;
} else {
$string = preg_replace('/\s/','',$string); //不进行替换则全部检查,遇到第一个不合格的词则返回该词
foreach ( $denywords as $deny ) { //遍历和谐词表
if ( stristr ( $string, $deny ) != false ) {
$res .= $deny . ',';
}
}
if ( empty( $res ) ) {
return false; //没有不合法的词
} else{
return $res;
}
}
}
敏感词过滤包