How to filter sensitive words in PHP
This article will explain in detail how to filter sensitive words in PHP. The content of the article is of high quality, so the editor shares it for you as a reference. I hope you will have a certain understanding of the relevant knowledge after reading this article.
1. Filtering method of sensitive words
/ * * @ todo sensitive words filter, return result * @ param array $list define sensitive words one-dimensional array * @ param string $string content to be filtered * @ return string $log processing result * / function sensitive ($list, $string) {$count = 0; / / number of illegal words $sensitiveWord =''; / / illegal words $stringAfter = $string; / / replaced content $pattern = "/" .implode ("|", $list). "/ I" / / define the regular expression if (preg_match_all ($pattern, $string, $matches)) {/ / match the result $patternList = $matches [0]; / / match the array $count = count ($patternList); $sensitiveWord = implode (',', $patternList); / / convert the array of sensitive words to the string $replaceArray = array_combine ($patternList,array_fill ($patternList),'*') / merge the matched arrays and replace them with $stringAfter = strtr ($string, $replaceArray); / / replace the result} $log = "the original sentence is [{$string}]"; if ($count==0) {$log. = "No sensitive words have been matched yet!" ;} else {$log. = "match to [{$count}] sensitive words: [{$sensitiveWord}]". "replaced by: [{$stringAfter}]";} return $log;}
2. Call method
Function testAction () {$string = 'likeyou Xiaobai loves rhubarb'; / / content to be filtered $list = ['Xiao Ming', 'Xiao Hong','Da Bai', 'Xiao Bai', 'Xiao Hei', 'me',' you']; / / define sensitive words array $result = $this- > sensitive ($list, $string); echo ($result); die / / print result: / * the original sentence is "likeyou Xiaobai likes rhubarb loved by Xiaobai] matches to [3] sensitive words: [you, Xiaobai, Xiaohei] is replaced by: [like** likes * beloved rhubarb] * /} about how to filter sensitive words in PHP. I hope the above content can be helpful to you and learn more. If you think the article is good, you can share it for more people to see.