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

资源魔 30 0
媒介:作为一位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开发资料 php开发自学 敏感词过滤

抱歉,评论功能暂时关闭!