php关键字过滤类

  1. <?php
  2. class fillter{
  3. private $keyword_file;
  4. private $dict;
  5. public $result;
  6. public function __construct($file){
  7. if(!is_file($file)){
  8. trigger_error("$file not exists!");
  9. }
  10. $this->keyword_file=$file;
  11. }
  12. public function fill($resource){
  13. $this->dict = $this->getDict();
  14. $len = strlen($resource);
  15. for($i=0; $i<$len; ++$i){
  16. $key=substr($resource,$i,2);
  17. if(array_key_exists($key,$this->dict)){
  18. $this->deal(substr($resource,$i,$this->dict[$key]['max']),$key,$af);
  19. $i+=$af;
  20. }
  21. else{
  22. $this->result .=substr($resource,$i,1);
  23. }
  24. }
  25. return $this->result;
  26. }
  27. public function deal($res,$key,&$af){
  28. $af=0;
  29. foreach($this->dict[$key]['list'] as $keyword){
  30. if(strpos($res,$keyword) !==false){
  31. $len=strlen($keyword);
  32. $af=$len-1;
  33. $this->result .=str_repeat("*",$len);
  34. return;
  35. }
  36. }
  37. $this->result .= substr($res,0,1);
  38. }
  39. private function getKeyWordList(){
  40. $keywords = file_get_contents($this->keyword_file);
  41. return array_unique(explode("\r\n",$keywords));
  42. }
  43. public function getDict(){
  44. $keywords=$this->getKeyWordList();
  45. $dict=array();
  46. foreach($keywords as $keyword){
  47. if(empty($keyword)){
  48. continue;
  49. }
  50. $key = substr($keyword,0,2);
  51. $dict[$key]['list'][]=$keyword;
  52. $dict[$key]['max']=max($dict[$key]['max'],strlen($keyword));
  53. }
  54. return $dict;
  55. }
  56. }
  57. //测试用demo 结果比直接用正则提高了3倍效率
  58. $res = $text = file_get_contents("test.txt");
  59. $t1 = microtime(true);
  60. $fil = new fillter("banwords.txt");
  61. $res = $fil->fill($text);
  62. //$res = $fil->getDict();
  63. //$keywords = explode("\r\n",file_get_contents("banwords.txt"));
  64. //foreach($keywords as $keyword){
  65. // if(empty($keyword)){
  66. // continue;
  67. // }
  68. // $res = preg_replace("/$keyword/","***",$res);
  69. //}
  70. $t2 = microtime(true);
  71. echo $t2-$t1;
  72. echo $text,"<br/>";
  73. echo "<pre>";
  74. print_r( $res);
  75. echo "</pre>";
  76. ?>

 青春就应该这样绽放  游戏测试:三国时期谁是你最好的兄弟!!  你不得不信的星座秘密
posted @ 2012-06-07 00:25  goodlad  阅读(1078)  评论(0)    收藏  举报