preg_replace 个单词有例外

preg_replace word with exception

我在这里和其他网站上阅读了很多帖子,以便使用 preg_replace 创建半工作脏话过滤器,如下所示:

function swearwords($word){
    $word = preg_replace('/\bwwww.badword.com\b/', '', $word); //do not remove \b //to add more copy and put word down
    $word = preg_replace('/\bwww.badword.com\b/', '', $word); //do not remove \b //to add more copy and put word down
    $word = preg_replace('/\bbadword\b/', '', $word); //do not remove \b //to add more copy and put word down
    //$word = preg_replace('/\bimg.badword``\b/', '', $word); //do not remove \b //to add more copy and put word down
    return $word;
}

这是可行的,但我想允许 img.badword

的实例

所以在“badword”之前有 .img 的地方,我想允许使用

这里是 'negative lookbehind' 断言的解决方案:

...
$word = preg_replace('/\b(?<!img\.)badword\b/', '', $word);
...

您也可以尝试以下一体式替换:

function swearwords($word){
    $word = preg_replace('/\b(w{3,4}\.)*(?<!img\.)badword(\.com)*\b/', '', $word);
    return $word;
}

http://php.net/manual/en/regexp.reference.assertions.php