当前位置:首页 > PHP

php实现词语过滤

2026-02-16 05:49:12PHP

PHP实现词语过滤的方法

使用PHP实现词语过滤可以通过多种方式完成,以下是几种常见的方法:

使用str_replace函数进行简单替换

$text = "这是一段包含敏感词的文本";
$badWords = ["敏感词", "不良词"];
$replacement = "*";
$filteredText = str_replace($badWords, $replacement, $text);

使用正则表达式进行更复杂的匹配

$text = "包含SensitiveWord的文本";
$pattern = '/sensitiveword/i'; // i表示不区分大小写
$filteredText = preg_replace($pattern, '*', $text);

创建自定义过滤函数

function filterWords($text, $badWords, $replacement = '*') {
    foreach($badWords as $word) {
        $pattern = '/'.preg_quote($word, '/').'/i';
        $text = preg_replace($pattern, $replacement, $text);
    }
    return $text;
}

$text = "测试敏感词过滤功能";
$badWords = ["敏感词", "测试"];
echo filterWords($text, $badWords);

使用数组和匿名函数进行高效过滤

$text = "这段文本需要过滤badword1和BADWORD2";
$badWords = ['badword1', 'badword2'];
$filteredText = array_reduce($badWords, function($carry, $word) {
    return preg_replace("/$word/i", '*', $carry);
}, $text);

从文件或数据库加载敏感词列表

// 从文件加载
$badWords = file('badwords.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

// 从数据库加载
$pdo = new PDO('mysql:host=localhost;dbname=test', 'user', 'pass');
$stmt = $pdo->query('SELECT word FROM bad_words');
$badWords = $stmt->fetchAll(PDO::FETCH_COLUMN);

使用mb_string函数处理多字节字符

$text = "包含日本語の不適切な言葉";
$badWords = ["不適切", "言葉"];
foreach($badWords as $word) {
    if(mb_strpos($text, $word) !== false) {
        $text = str_replace($word, '*', $text);
    }
}

实现模糊匹配过滤

function fuzzyFilter($text, $badWords, $threshold = 70) {
    foreach($badWords as $word) {
        similar_text(strtolower($text), strtolower($word), $percent);
        if($percent >= $threshold) {
            $text = preg_replace('/'.$word.'/i', '*', $text);
        }
    }
    return $text;
}

使用第三方库

可以考虑使用专门的过滤库如:

  • voku/stop-words
  • james-heinrich/php-stop-words

这些方法可以根据具体需求选择或组合使用,实现不同级别的词语过滤功能。

php实现词语过滤

标签: 词语php
分享给朋友:

相关文章

php实现分页

php实现分页

PHP实现分页的基本方法 使用LIMIT和OFFSET进行数据库查询分页。通过计算当前页码和每页显示数量,动态生成SQL语句。 $page = isset($_GET['page']) ? (in…

git php实现

git php实现

Git 与 PHP 的集成实现 使用 PHP 执行 Git 命令 通过 PHP 的 exec()、shell_exec() 或 passthru() 函数可以直接调用 Git 命令,适用于服务器端操作…

php实现定时任务

php实现定时任务

PHP 实现定时任务的几种方法 在 PHP 中实现定时任务可以通过多种方式完成,具体选择取决于项目需求和服务器环境。以下是常见的实现方法: 使用 Cron 任务 Cron 是 Linux 系统中常用…

php实现websocket

php实现websocket

PHP 实现 WebSocket WebSocket 是一种在单个 TCP 连接上进行全双工通信的协议。PHP 可以通过多种方式实现 WebSocket 功能,以下是几种常见的方法: 使用 Rat…

php长连接实现

php长连接实现

PHP 长连接实现方法 长连接(Keep-Alive)允许客户端与服务器在一次TCP连接中发送和接收多个HTTP请求/响应,减少重复建立连接的开销。以下是PHP中实现长连接的几种方式: 配置HT…

php实现搜索

php实现搜索

PHP实现搜索功能的方法 在PHP中实现搜索功能通常涉及数据库查询和用户输入的匹配。以下是几种常见的实现方式: 使用MySQL LIKE语句 通过简单的LIKE语句实现基础搜索: $searchT…