PHP 敏感词过滤 轮子 |2019-01-18

https://laravel-china.org/articles/5855/write-a-filter-for-sensitive-words

    /***
     * 敏感词过滤
     * 有敏感词 则返回 具体敏感词汇
     * 无敏感词 返回 no
     ***/
    function sensitiveWordFilter($str)
    {
        // $words = getSensitiveWords();
        $words = ['敏感词1', '敏感词2','敏感词3'];//建议从数据库获取
        $flag = false;

        // 提取中文部分,防止其中夹杂英语等
        preg_match_all("/[\x{4e00}-\x{9fa5}]+/u", $str, $match);
        $chinsesArray = $match[0];
        $chineseStr = implode('', $match[0]);
        $englishStr = strtolower(preg_replace("/[^A-Za-z0-9\.\-]/", " ", $str));

        $flag_arr = array('?', '!', '¥', '(', ')', ':' , '‘' , '’', '“', '”', '《' , '》', ',',
            '…', '。', '、', 'nbsp', '】', '【' ,'~', '#', '$', '^', '%', '@', '!', '*', '-'. '_', '+', '=');
        $contentFilter = preg_replace('/\s/', '', preg_replace("/[[:punct:]]/", '',
            strip_tags(html_entity_decode(str_replace($flag_arr, '', $str), ENT_QUOTES, 'UTF-8'))));

        // 全匹配过滤,去除特殊字符后过滤中文及提取中文部分
        foreach ($words as $word)
        {
            // 判断是否包含敏感词,可以减少这里的判断来降低过滤级别,
            if (strpos($str, $word) !== false || strpos($contentFilter, $word) !== false || strpos($chineseStr, $word) !== false
                || strpos($englishStr, $word) !== false) {
                return '敏感词:' . $word;
            }
        }
        return $flag ? 'yes' : 'no';
    }

当你的敏感字词库多了之后就 gg 了.

推荐这个:
https://www.v2ex.com/t/120889

https://github.com/nowgoo/dict

给自己打个广告, 参考上面这个库的实现方式做的一个邮箱地址过滤器:

https://github.com/RunnerLee/email-address-filter

猜你喜欢

转载自blog.csdn.net/weixin_33724059/article/details/87510966
今日推荐