PHP - 过滤敏感词汇

方法一:

$sensitive = array(
    '小白', '小黑', 'me', 'you'
);
$badword = array_combine($sensitive,array_fill(0,count($sensitive),'*'));
$string = 'likeyou小白喜欢小黑爱着的大黄';
$str = strtr($string, $badword);
echo $str;

方法二:

function sensitive($list, $string){
    $count = 0; //违规词的个数
    $sensitiveWord = '';  //违规词
    $stringAfter = $string;  //替换后的内容
    $pattern = "/".implode("|",$list)."/i"; //定义正则表达式

    if(preg_match_all($pattern, $string, $matches)){ //匹配到了结果
        $patternList = $matches[0];  //匹配到的数组
        $count = count($patternList);
        $sensitiveWord = implode(',', $patternList); //敏感词数组转字符串
        $replaceArray = array_combine($patternList,array_fill(0,count($patternList),'*')); //把匹配到的数组进行合并,替换使用
        $stringAfter = strtr($string, $replaceArray); //结果替换
    }
    $log = "原句为 [ {$string} ]<br/>";
    if($count==0){
        $log .= "暂未匹配到敏感词!";
    }else{
        $log .= "匹配到 [ {$count} ]个敏感词:[ {$sensitiveWord} ]<br/>".
            "替换后为:[ {$stringAfter} ]";
    }
    return $log;
}

function testAction(){
    $string = 'likeyou小白喜欢小黑爱着的大黄'; //要过滤的内容
    $list = ['小明', '小红', '大白', '小白', '小黑', 'me', 'you'];  //定义敏感词数组
    $result = sensitive($list, $string);
    echo ($result);
    die;
}

方法三:

<?php
/**
 * 敏感词过滤方法.
 */

namespace app\common\tool;


use app\common\model\Sensitive;

class SensitiveTool
{
    private static $arrHashMap = [];
    private static $file       = ROOT_PATH.'runtime'.DS.'sensitive.txt';

    /**
     * 把敏感词保存为文件
     * @return bool|int
     */
    public static function saveSensitiveWord(){
        $data = Sensitive::all();
        foreach( $data as $k => $v ){
            self::addKeyWord($v['name']);
        }
        return file_put_contents(self::$file,serialize(self::$arrHashMap));

    }

    /**
     * 过滤敏感词
     * @param $strWord
     * @return mixed
     */
    public static function filterSensitiveWord( $strWord ){
        $file = unserialize(file_get_contents(self::$file));
        $resStr  = $strWord;
        if(!empty($file)){
            $len = mb_strlen($strWord, 'UTF-8');
            $arrHashMap = self::$arrHashMap = $file;
            $newWord = '';
            for ($i=0; $i < $len; $i++) {
                $word = mb_substr($strWord, $i, 1, 'UTF-8');
                if (!isset($arrHashMap[$word])) {
                    $arrHashMap = self::$arrHashMap;
                    $newWord = '';
                }
                $newWord .= $word;
                if ($arrHashMap[$word]['end']) {
                    $asterisk = self::getAsterisk(mb_strlen($newWord, 'UTF-8'));
                    $resStr = str_replace($newWord,$asterisk,$resStr);
                    $newWord = '';
                    $arrHashMap = self::$arrHashMap;
                } else{
                    $arrHashMap = $arrHashMap[$word];

                }
            }
        }

        return $resStr;
    }

    /**
     * 过滤邮箱和手机号(8位以上数字)
     * @param $msg
     * @return string
     */
    public static function filterTelMail( $msg ):string {
        if(is_string((string)$msg)){
            $msg = preg_replace('/\d{8,}/', '****', $msg);
            $msg = preg_replace('/[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})/i', '****', $msg);
        }else{
            $msg = '';
        }

        return $msg;
    }
    /**
     * 新增敏感词的核心方法
     * @param $strWord
     */
    private static function addKeyWord( $strWord ) { //免定金峨眉牌汽枪
        $len = mb_strlen($strWord, 'UTF-8');

        $arrHashMap = &self::$arrHashMap;
        for ($i=0; $i < $len; $i++) {
            $word = mb_substr($strWord, $i, 1, 'UTF-8');
            // 已存在
            if (isset($arrHashMap[$word])) {
                if ($i == ($len - 1)) {
                    $arrHashMap[$word]['end'] = 1;
                }
            } else {
                // 不存在
                if ($i == ($len - 1)) {
                    $arrHashMap[$word] = [];
                    $arrHashMap[$word]['end'] = 1;
                } else {
                    $arrHashMap[$word] = [];
                    $arrHashMap[$word]['end'] = 0;
                }
            }
            // 传址
            $arrHashMap = &$arrHashMap[$word];
        }
    }

    /**
     * 生成*号
     * @param int $num
     * @return string
     */
    private static function getAsterisk( int $num ) :string {
        $str = '';
        for($i=1;$i<=$num;$i++) {
            $str .= '*';
        }
        return $str;
    }

}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值