如何用php替换坏词? [英] How do I replace bad words with php?

查看:72
本文介绍了如何用php替换坏词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一些文字来过滤掉一系列坏词,例如:

I have some text i need to filter out a list of bad words in like:

$bad_words = array(
  'word1' => 'gosh',
  'word2' => 'darn',
);

我可以循环浏览并一次替换一个,但是那很慢吧?有更好的方法吗?

I can loop through these and replace one at a time but that is slow right? Is there a better way?

推荐答案

是的.使用 preg_replace_callback() :

Yes there is. Use preg_replace_callback():

<?php
header('Content-Type: text/plain');

$text = 'word1 some more words. word2 and some more words';
$text = preg_replace_callback('!\w+!', 'filter_bad_words', $text);
echo $text;

$bad_words = array(
  'word1' => 'gosh',
  'word2' => 'darn',
);

function filter_bad_words($matches) {
  global $bad_words;
  $replace = $bad_words[$matches[0]];
  return isset($replace) ? $replace : $matches[0];
}
?>

这是一个简单的过滤器,但有很多限制.就像这样,它不会阻止拼写,字母之间使用空格或其他非单词字符,用数字替换字母等方面的变化.但是,您希望它变得多么复杂基本上取决于您.

That is a simple filter but it has many limitations. Like it won't stop variations on spelling, use of spaces or other non-word characters in between letters, replacement of letters with numbers and so on. But how sophisticated you want it to be is up to you basically.

我意识到这已经有7年了,但是如果要测试的单词不在$bad_words数组中,则较新版本的php似乎会引发异常.为了解决这个问题,我对filter_bad_words()的最后两行进行了如下更改:

I realize this is 7 years old, but newer versions of php seem to throw an exception if the word being tested is not in the $bad_words array. To fix this, I have changed the last two lines of filter_bad_words() as follows:

$replace = array_key_exists($matches[0], $bad_words) ? $bad_words[$matches[0]] : false;
return $replace ?: $matches[0];

这篇关于如何用php替换坏词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆