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

PHP implements the replacement operation of special characters

王林
王林 Original
2019-08-15 11:04:09 4470browse

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文件中 肮脏fsdf污秽d 骂人' //判断是否替换成功 if($result = Replace($content, './words.txt')) { echo $result; echo '替换成功!'; }else { echo '替换失败!'; } ?>

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