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

php如何实现特殊字符的替换操作?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

实例:

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

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如何实现特殊字符的替换操作问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注行业资讯频道了解更多相关知识。