str_replace 仅替换匹配词

str_replace replace only match words

我有这个 PHP 函数可以用一些词替换列表文件中文本中的词

我的函数

function replace_text_wps($text){

$dir = plugin_dir_path( __FILE__ );
   $file= $dir."bad2.list";

$badlist = file($file, FILE_IGNORE_NEW_LINES);
$replace = '[censored]';

    $text = str_replace($badlist, $replace, $text);
    return $text;
}

例如我的 bad2.list

中有单词 ABC

当我输入文本 ABC 时,我的函数将 ABC 更改为 [censored] ,但如果我输入单词 DFGABC 将其更改为 DFG[censored]

如何只替换文件中的匹配词? 我是 PHP 的新人?抱歉新手问题

更新:

HD, thank you! your solution 适合我!

这是工作版

function replace_text_wps($text){

$dir = plugin_dir_path( __FILE__ );
   $file= $dir."bad2.list";

$badlist = file($file, FILE_IGNORE_NEW_LINES);

$replacement = "[CENSORED]";
$badlist = array_map(function($v) { return "\b". $v ."\b"; }, $badlist);
foreach($badlist as $f) {
    $text = preg_replace("/".$f."/u", $replacement, $text);


    return $text;
}

你可以使用一个数组,所以如果你的 bad2.list 文件每一行都有里面的所有 'bad' 个词,所以就像每行一个词一样,你可以做一些事情像这样:

$file = file_get_contents("bad2.list"); //Should be a .txt....
$words = explode("\n", $file); //Explodes into a Array on each new line.

$message = "DFGABC";

foreach($words AS $word){
    $message = str_replace($word, "[censored]", $message);
}

echo $message;

一种可能的解决方法是在您要审查的词后添加 space,或者您可以通过在 str_replace();[=13 之前添加 $word = $word.' '; 来自动执行此操作=]

以下将按照您的要求工作。

您可以改用preg_replace()

$replace = '[censored]';

    $text = preg_replace("/\b$text\b/", $replace, $badlist);
    return $text;

这里有几个相互矛盾的问题,其中一些是由 提出的。

这是一个定义什么是单词的案例,你可能认为"yes, this is a word"包含5个单词,但如果你使用空格系统来区分单词,比如

$badwords = array(" yes ", " this "); 
$text = "yes, this is a word"; 
print str_replace($badwords, "[censored]", $text);

输出将是 "yes, [censored] is a word";

因为空格没有定义字形;单词可以换行,从换行符 \n 到句号,各种标点符号,甚至没有空格,试试上面的相同系统,但是:

$text = "this";

它不会替换有问题的词,因为该词没有整齐地包裹在每一边的空格中。

还有你把连字符定义为分词的问题吗? "yes-sir" 是您要从中替换 "yes" 的词吗?或者只有当 yes 是一个单一的单词实体时? ...这让我想起了当我看到一个在线约会网站删除了 "cocktails" 这个词,因为它包含一个粗鲁的词。

所以....我们怎样才能做到这一点?

正则表达式匹配,使用PHP函数preg_replace and reading this stack overflow question and answers。我认为没有必要在这里重复该问题中的内容,但更多的是 post 是关于概述尝试使用简单的字符串替换函数进行正则表达式智能查找和替换的众多陷阱。

Regex Example


另请注意,您当前的函数 区分大小写 因此您不会匹配 CaMelcaSe 或大写版本的坏词.

而且,如果您懒惰地决定简单地在搜索中添加空格,您必须记住,您还需要添加相同的空格以保留 替换 文本的格式出色地。

更新:

HD, thank you! your solution 适合我!

这是工作版

function replace_text_wps($text){

$dir = plugin_dir_path( __FILE__ );
   $file= $dir."bad2.list";

$badlist = file($file, FILE_IGNORE_NEW_LINES);

$replacement = "[CENSORED]";
$badlist = array_map(function($v) { return "\b". $v ."\b"; }, $badlist);
foreach($badlist as $f) {
    $text = preg_replace("/".$f."/u", $replacement, $text);


    return $text;
}