php过滤敏感词
<?php
/**
* created by jetbrains phpstorm.
* user: lsl
* date: 13-8-28
* time: 下午2:58
* 敏感词过滤工具类
* 使用方法
* echo filtertools::filtercontent("你妈的我操一色狼杂种二山食物","*",dir."config/word.txt",$globals["p_memcache"]["bad_words"]);
*/
class filtertools {
public static $keyword = array();
/**
* 从文件中加载敏感词
* @param $filename
* @return array
*/
static function getbadwords($filename){
$file_handle = fopen($filename, "r");
while (!feof($file_handle)) {
$line = trim(fgets($file_handle));
array_push(self::$keyword,$line);
}
fclose($file_handle);
return self::$keyword;
}
/**
* @param $content 待处理字符串
* @param $target 替换后的字符
* @param $filename 敏感词配置文件
* @param $memconfig 缓存配置文件
* @return 处理后的字符串
*/
static function filtercontent($content,$target,$filename,$memconfig){
$mem = new badwordsmemcache($filename,$memconfig);
$keyword = $mem->getlist();
if(count($keyword) == 0){
$keyword = self::getbadwords($filename);
}
return strtr($content, array_combine( $keyword, array_fill(0,count($keyword), $target)));
}
}
/**
* 敏感词缓存处理类
* class badwordsmemcache
* user: lsl
*/
class badwordsmemcache{
var $memcache;
var $key;
var $list;
var $filename;
function __construct($filename,$memconfig) {
$this->filename = $filename;
if(!class_exists("p_memcache")){
require_once dir."lib/memcache.class.php";
}
$this->key = "bad_words";
$this->memcache = new p_memcache();
$this->memcache->config = $memconfig;
$this->memcache->connect();
print_r($this->memcache);
$this->init();
}
function __destruct() {
$this->memcache->close();
}
/**
* 初始化
* @param bool $isreset
*/
function init($isreset = false){
$this->list = $this->memcache->get($this->key)?$this->memcache->get($this->key):array();
if(count($this->list)==0 || $isreset){
$this->list = filtertools::getbadwords($this->filename);
$this->memcache->set($this->key, $this->list);
$log_data = log::formatdata($this->list);
log::logwrite($log_data, 'bad.words','init');
}
}
/**
* 获取列表
* @return mixed
*/
function getlist(){
return $this->list;
}
}