search
HomeBackend DevelopmentPHP TutorialPHP filter sensitive word example code_PHP tutorial


  /**
* Created by JetBrains PhpStorm.
* User: lsl
* Date: 13-8-28
* Time: 2:58 PM
* Sensitive word filtering tools
* How to use
* echo FilterTools::filterContent("Fuck you, I’m a pervert bastard Ershan Food","*",DIR."config/word.txt",$GLOBALS["p_memcache" ]["bad_words"]);
*/ 
   
  class FilterTools { 
      public static $keyword = array(); 
      /**
* Load sensitive words from the file
* @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; 
      } 
  } 

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/371371.htmlTechArticle?php /** *CreatedbyJetBrainsPhpStorm. *User:lsl *Date:13-8-28 *Time:下午2:58 *敏感词过滤工具类 *使用方法 *echoFilterTools::filterContent(quot;你妈的我操一色狼杂...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.