Example of Sensitive Word Filtering Method Implemented by PHP

  • 2021-11-29 06:31:19
  • OfStack

In this paper, an example is given to describe the sensitive word filtering method implemented by PHP. Share it for your reference, as follows:

1. Sensitive word filtering method


/**
 * @todo  Sensitive word filtering, return results 
 * @param array $list   Defining Sensitive Words 1 Dimensional array 
 * @param string $string  Content to filter 
 * @return string $log  Processing result 
 */
function sensitive($list, $string){
  $count = 0; // Number of illegal words 
  $sensitiveWord = '';  // Illegal words 
  $stringAfter = $string;  // Content after replacement 
  $pattern = "/".implode("|",$list)."/i"; // Defining regular expressions 
  if(preg_match_all($pattern, $string, $matches)){ // Matched the result 
    $patternList = $matches[0];  // Matched array 
    $count = count($patternList);
    $sensitiveWord = implode(',', $patternList); // Sensitive word array to string 
    $replaceArray = array_combine($patternList,array_fill(0,count($patternList),'*')); // Merge the matched arrays and replace them with 
    $stringAfter = strtr($string, $replaceArray); // Result substitution 
  }
  $log = " The original sentence is  [ {$string} ]<br/>";
  if($count==0){
    $log .= " Sensitive words have not been matched yet! ";
  }else{
    $log .= " Match to  [ {$count} ] Sensitive words: [ {$sensitiveWord} ]<br/>".
      " After replacement: [ {$stringAfter} ]";
  }
  return $log;
}

2. Call the method


function testAction(){
  $string = 'likeyou Xiaobai likes the rhubarb that Xiaobei loves '; // Content to filter 
  $list = [' Xiao Ming ', ' Xiao Hong ', ' Big white ', ' Xiaobai ', ' Xiao Hei ', 'me', 'you'];  // Defining an array of sensitive words 
  $result = $this->sensitive($list, $string);
  echo ($result);
  die;
  // Print results: 
  /*
   The original sentence is  [ likeyou Xiaobai likes the rhubarb that Xiaobei loves  ]
   Match to  [ 3 ] Sensitive words: [ you, Xiaobai , Xiao Hei  ]
   After replacement: [ like** Like * Loving rhubarb  ]
    */
}

PS: Here are two very convenient regular expression tools for your reference:

JavaScript Regular Expression Online Test Tool:
http://tools.ofstack.com/regex/javascript

Regular expression online generation tool:
http://tools.ofstack.com/regex/create_reg

More readers interested in PHP can check out the topics of this site: "Summary of php Regular Expression Usage", "php Programming Security Tutorial", "php Security Filtering Skills Summary", "PHP Array (Array) Operation Skills Encyclopedia", "PHP Basic Syntax Introduction Tutorial", "php String (string) Usage Summary" and "php+mysql Database Operation Introduction Tutorial"

I hope this article is helpful to everyone's PHP programming.


Related articles: