php实现特殊字符的替换操作

2020-08-28

前言:作为一名phper,对于字符串的操作是必须要掌握的,因此,我们就会接触到如何替换或者屏蔽字符串中的敏感词问题,接下来,就为大家介绍一下替换的方法。文章仅供参考,谢谢!

实例:

第一步:在字符串中搜索有无敏感词

int substr_count(string haystack,string needle)

substr_count() 函数检索子串出现的次数,参数haystack是指定的字符串,参数needle为指定的字符。

//定义敏感词数组
$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;
}

第二步:使用preg_replace()函数实现敏感词的替换

preg_replace()函数执行一个正则表达式的搜索和替换

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('文件获取失败!');
}
//取出成功,将字符串改成小写
$string = strtolower($str);
$word = preg_replace('/[1,2,3]\r\n|\r\n/i','',$words);
//字符串中出现文本敏感词,用特殊符号替换
$match = preg_replace('/'.$word.'/i','***',$string);
return $match;
}
//定义包含敏感词的字符串
$content = '<a href="#">肮脏fsdf污秽d 骂人</a>'
//判断是否替换成功
if($result = Replace($content, './words.txt')) {
echo $result;
echo '替换成功!';
}else {
echo '替换失败!';
}
?>

以上就是php实现特殊字符的替换操作的详细内容,更多请关注北冥有鱼其它相关文章!

本文转载自【PHP中文网】,希望能给您带来帮助,苟日新、日日新、又日新,生命不息,学习不止。

《php实现特殊字符的替换操作.doc》

下载本文的Word格式文档,以方便收藏与打印。