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


PHP: file to array check and replace

我有这样的代码,它应该首先将整个单词文件处理成一个数组,然后检查文件中任何单词的字符串。如果匹配,则用*替换。

该文件类似于:

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;
}

因此,原句中确实有一些吟游诗人的话,但为了张贴而删除了。

感谢

在函数定义中,您可以调用单词列表$filterArray

function filterwords($text, $filterArray){

但在整个函数中,您将其称为$filterWords

在定义中将其重命名为$filterWords,或者将每个出现的项重命名为$filterArray

在忽略空行的情况下构建$filterWords。您实际上需要FILE_IGNORE_NEW_LINESFILE_SKIP_EMPTY_LINES

$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_replace():

$textToPrint = preg_replace($patterns, $replacements, $comment);

这将从CCD_ 10产生CCD_ 9。