Home > Article > Backend Development > How to shield and filter specified keywords in PHP, PHP shields and filters keywords_PHP tutorial
The example in this article describes the method of blocking and filtering specified keywords in PHP. Share it with everyone for your reference. The specific analysis is as follows:
Implementation ideas:
1. Write the keywords specifically in a text file, one per line. There is no limit to the number. Write as many as you want.
2. PHP reads the keyword text and stores it in an array
3. Traverse the keyword array and use the strpos function one by one to see if there are keywords in the content. If there are keywords, return true, if not, return false
The PHP code is as follows:
Example 2 (Note: The keyword file used when filtering Chinese keywords is utf-8 encoded)
I hope this article will be helpful to everyone’s PHP programming design.
To determine whether a certain text contains a certain string or certain strings, you can use preg_match to judge. For message books or forums, you can judge whether it contains certain sensitive keywords to decide whether to filter and allow it. Publish
Separate each sensitive word with the symbol "|", because in the regular expression "|" is equivalent to the meaning of "or"
$ badkey = "sensitive word|sensitive word B|sensitive word C";
$string = "I do not contain sensitive words, I want to publish";
if(preg_match("/ $badkey/i",$string)){
echo "Sorry, it contains sensitive characters and is not allowed to be published";
}else{
//do something ...
}
?>
And preg_replace can be used for keyword filtering (dirty words filtering)
php can use preg_replace Filter bad words
$badstring="tmd|damn|TNND|her motherfucker";
$string="What did you tmd say, her motherfucker, Not a human";
echo preg_replace("/$badstring/i",'',$string);
?>
$allergicWord = array('cussing','cussing');
$str = 'This sentence contains swearing and swearing';
for ($i=0; $i
if($content>0){
$info = $ content;
break;
}
}
if($info>0){
//There are illegal characters
return TRUE;
}else{
//No illegal characters
return FALSE;
}
?>
Version:
html>
head>
/head>
form action="" method="post" name="form1" >
input name="word" type="text" />
input name="" type="submit" onclick="return chkValue();" value="Confirm"/>
/form>
script type="text/javascript">
function chkValue() {
var val = document.form1.word.value,
array = ["acd","svd"," fdg","fdk"];
for( var i = array.length; i--;) {
if( val.indexOf( array[i] ) !== -1 ) {
alert('There are sensitive characters:' + array[i]);
return false;
}
}
return true;
}
/script>
/html> ;
PHP version
?php
$content = "afjvahsv sjv sdjavcvacvdjgfsacdaldkfja sfcjasldfj ";
$keyword = array( "acd","svd","fdg", "fdk" );
for( $i = count($keyword); $i--; ) {
if( strpos( $content, $keyword[$i] ) !== false ) {
echo "Sensitive characters appear: {$keyword[$i]}";exit();
}
}
?>
A hundred generations of contemporary times are good for eternity Jiangshan Jinzhao New Vientiane Update