Home >Backend Development >PHP Tutorial >PHP implements the replacement operation of special characters

PHP implements the replacement operation of special characters

王林
王林Original
2019-08-15 11:04:094585browse

Preface:As a phper, you must master the operation of strings. Therefore, we will come into contact with the issue of how to replace or block sensitive words in strings. Next, we will Let me introduce to you the replacement method. The article is for reference only, thank you!

Example:

Step 1: Search for sensitive words in the string

int substr_count(string haystack,string needle)

substr_count() function retrieves the occurrence of substrings times, the parameter haystack is the specified string, and the parameter needle is the specified character.

//定义敏感词数组
$array = array('骂人','肮脏','污秽');
//定义包含敏感词的字符串
$mgstr = '这是包含骂人肮脏污秽的话';
//利用循环判断字符串是否包含敏感词
for($i = 0; $i <= count($array); $i++) {
$count = substr_count($mgstr, $array);
if($count > 0) {
$info = $count;
break;
}
}
if($info > 0) {
//有敏感字符
return true;
}else{
//无敏感字符
return false;
}

Step 2: Use the preg_replace() function to replace sensitive words

preg_replace() function performs a regular expression search and replacement

mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )
//关键词存放在.txt文件中
<?php
//自定义替换函数
function Replace($str, $filenam){
if(!($words = file_get_contents($filename))) {
//将敏感词语文本取出
die(&#39;文件获取失败!&#39;);
}
//取出成功,将字符串改成小写
$string = strtolower($str);
$word = preg_replace(&#39;/[1,2,3]\r\n|\r\n/i&#39;,&#39;&#39;,$words);
//字符串中出现文本敏感词,用特殊符号替换
$match = preg_replace(&#39;/&#39;.$word.&#39;/i&#39;,&#39;***&#39;,$string);
return $match;
}
//定义包含敏感词的字符串
$content = &#39;<a href="#">肮脏fsdf污秽d 骂人</a>&#39;
//判断是否替换成功
if($result = Replace($content, &#39;./words.txt&#39;)) {
echo $result;
echo &#39;替换成功!&#39;;
}else {
echo &#39;替换失败!&#39;;
}
?>

The above is the detailed content of PHP implements the replacement operation of special characters. For more information, please follow other related articles on the PHP Chinese website!

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