php过滤短语

php过滤短语,php,filter,Php,Filter,如何使用php过滤短语?有人能给我一个函数调用吗 例如,如果我想从句子中筛选短语“no”“this”,则此页面没有用户提供的注释。 因此,返回的句子类似于页面有用户提供的注释。谢谢 <?php function filterBadWords($str) { $badwords = array('no','this'); $replacements = " "; foreach ($badwords AS $badword) { $str

如何使用php过滤短语?有人能给我一个函数调用吗

例如,如果我想从句子中筛选短语“no”“this”,则此页面没有用户提供的注释。

因此,返回的句子类似于
页面有用户提供的注释。
谢谢

<?php
function filterBadWords($str)
{
    $badwords = array('no','this');
    $replacements = " ";
    foreach ($badwords AS $badword)
    {
          $str = eregi_replace($badword, str_repeat(' ', strlen($badword)), $str);
    }  
    return $str;
} 

$string = "There are user contributed notes for page.";
print filterBadWords($string); // this will filter `no` from `notes`
?>

编辑:

现在,如果在单词后面找到一个空格,它会删除一个空格,这样就不会在一行中有两个空格

$text = 'There are no user contributed notes for this page.';
$text = preg_replace('/\b(?:no|this)\b ?/i', '', $text);
echo $text;
输出:页面上有用户提供的注释

更新

如果要使用数组更容易管理过滤词,可以执行以下操作:

function filterWords($string){
    $bad_words = array('no', 'this');
    return preg_replace('/\b(?:'.implode('|', $bad_words).')\b ?/i', '', $string);
}

echo filterWords('There are no user contributed notes for this page.');
使用

echo stru_replace(数组('no','this'),'',没有用户为此页面提供的注释')//页面上有用户贡献的TE始终断开
注释
并成为
tes
function filterWords($string){
    $bad_words = array('no', 'this');
    return preg_replace('/\b(?:'.implode('|', $bad_words).')\b ?/i', '', $string);
}

echo filterWords('There are no user contributed notes for this page.');
str_replace(array('no', 'this'), '', $text);