php过滤敏感词实例代码

php过滤敏感词实例代码

<?php

/**

* Created by JetBrains PhpStorm.

* User: lsl

* Date: 13-8-28

* Time: 下午2:58

* 敏感词过滤工具类

* 使用方法

* echo FilterTools::filterContent(&quot;你妈的我操一色狼杂种二山食物&quot;,&quot;*&quot;,DIR.&quot;config/word.txt&quot;,$GLOBALS[&quot;p_memcache&quot;][&quot;bad_words&quot;]);

*/

class FilterTools {

public static $keyword = array();

/**

* 从文件中加载敏感词

* @param $filename

* @return array

*/

static function getBadWords($filename){

$file_handle = fopen($filename, &quot;r&quot;);

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-&gt;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-&gt;filename = $filename;

if(!class_exists(&quot;P_Memcache&quot;)){

require_once DIR.&quot;lib/memcache.class.php&quot;;

}

$this-&gt;key = &quot;bad_words&quot;;

$this-&gt;memcache = new P_Memcache();

$this-&gt;memcache-&gt;config = $memconfig;

$this-&gt;memcache-&gt;connect();

print_r($this-&gt;memcache);

$this-&gt;init();

}

function __destruct() {

$this-&gt;memcache-&gt;close();

}

/**

* 初始化

* @param bool $isReset

*/

function init($isReset = false){

$this-&gt;list = $this-&gt;memcache-&gt;get($this-&gt;key)?$this-&gt;memcache-&gt;get($this-&gt;key):array();

if(count($this-&gt;list)==0 || $isReset){

$this-&gt;list = filterTools::getBadWords($this-&gt;filename);

$this-&gt;memcache-&gt;set($this-&gt;key, $this-&gt;list);

$log_data = Log::formatData($this-&gt;list);

Log::logWrite($log_data, 'bad.words','init');

}

}

/**

* 获取列表

* @return mixed

*/

function getList(){

return $this-&gt;list;

}

}