前言:作為一名phper,對于字符串的操作是必須要掌握的,因此,我們就會接觸到如何替換或者屏蔽字符串中的敏感詞問題,接下來,就為大家介紹一下替換的方法。文章僅供參考,謝謝!
實(shí)例:
第一步:在字符串中搜索有無敏感詞
int substr_count(string haystack,string needle)
substr_count() 函數(shù)檢索子串出現(xiàn)的次數(shù),參數(shù)haystack是指定的字符串,參數(shù)needle為指定的字符。
//定義敏感詞數(shù)組 $array = array('罵人','骯臟','污穢'); //定義包含敏感詞的字符串 $mgstr = '這是包含罵人骯臟污穢的話'; //利用循環(huán)判斷字符串是否包含敏感詞 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()函數(shù)實(shí)現(xiàn)敏感詞的替換
preg_replace()函數(shù)執(zhí)行一個正則表達(dá)式的搜索和替換
mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )
//關(guān)鍵詞存放在.txt文件中 <?php //自定義替換函數(shù) function Replace($str, $filenam){ if(!($words = file_get_contents($filename))) { //將敏感詞語文本取出 die('文件獲取失敗!'); } //取出成功,將字符串改成小寫 $string = strtolower($str); $word = preg_replace('/[1,2,3]rn|rn/i','',$words); //字符串中出現(xiàn)文本敏感詞,用特殊符號替換 $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 '替換失敗!'; } ?>