PHP:文件到数组检查和替换

PHP:文件到数组检查和替换,php,filter,Php,Filter,我有一段代码,它应该首先将整个单词文件处理成一个数组,然后检查传递的字符串中是否有这些单词。如果匹配,则替换为* 该文件类似于: wordalex wordjordan wordjohn .... 不幸的是,我传递的句子没有按照我期望的方式过滤。事实上,它什么也没发生。你能看一下给出的代码和帮助吗 $comment = "the wordalex if this doesn't get caught!"; $filterWords = file('badwords.txt', FILE_IGN

我有一段代码,它应该首先将整个单词文件处理成一个数组,然后检查传递的字符串中是否有这些单词。如果匹配,则替换为*

该文件类似于:

wordalex
wordjordan
wordjohn
....
不幸的是,我传递的句子没有按照我期望的方式过滤。事实上,它什么也没发生。你能看一下给出的代码和帮助吗

$comment = "the wordalex if this doesn't get caught!";
$filterWords = file('badwords.txt', FILE_IGNORE_NEW_LINES);
//print_r($filterWords);
$textToPrint = filterwords($comment,$filterWords );
echo $textToPrint;

function filterwords($text, $filterArray){
    $filterCount = sizeof($filterWords);
    for($i=0; $i<$filterCount; $i++){
        $text = preg_replace('/\b'.$filterWords[$i].'\b/ie',"str_repeat('*',strlen('$0'))",$text);
    }
    return $text;
}
$comment=“如果这个词没有被发现,请用alex!”;
$filterWords=file('badwords.txt',file\u IGNORE\u NEW\u行);
//打印(过滤词);
$textToPrint=filterwords($comment,$filterwords);
echo$textToPrint;
函数filterWord($text,$filterArray){
$filterCount=sizeof($FilterWord);

对于($i=0;$iBuild
$filterWords
而忽略空行。实际上,您需要
文件\u忽略\u新行
文件\u跳过\u空行

$filterWords = file('badwords.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
构建替换阵列:

$replacements = array();
$patterns = array();

foreach ($filterWords as $word) {
    // ignore empty words, just in case
    if (empty($word)) continue;        

    $replacements[] = str_repeat('*', strlen($word));
    $patterns[] = "/\b$word\b/i";
}
然后执行
preg\u replace()


这将从
Hello word john NOTwordjohn
中产生
Hello*********NOTwordjohn
,在函数定义中,调用单词列表
$filterary

function filterwords($text, $filterArray){
但在整个函数中,您将其称为
$filterWords


请在定义中将其重命名为
$filterWords
,或将每个引用重命名为
$filterArray

,谢谢,这确实有效…但它不进行正则表达式匹配…因此,如果我编写世界级,它将成为cl***。我希望它在这些单词是整个单词的一部分而不是它们自己的时候忽略它们:)使用
preg\u replace()
编辑以仅进行单词匹配。这与preg是相同的错误。有任何方法可以对其进行排序吗?非常感谢您的努力

警告:preg\u replace()[function.preg replace]:编译失败:在偏移量2I处无需重复。我实际上已尝试运行代码,没有任何错误。您的
$filterWords
真的是一个单词数组吗?我相信您的
$filterWords
中有空单词。只需编辑代码以忽略空单词。请尝试。
function filterwords($text, $filterArray){