You'll have to be careful with that approach. For instance, you risk censoring "grass" to "gr***" when you censor "ass".
You can "fix" that like this:
$badwords = array('bad1', 'bad2', 'bad3', 'ass');
$text = 'This is a test. Ass. Grass. bad1.';
function filterBadwords($text, array $badwords, $replaceChar = '*') {
return preg_replace_callback(
array_map(function($w) { return '/\b' . preg_quote($w, '/') . '\b/i'; }, $badwords),
function($match) use ($replaceChar) { return str_repeat($replaceChar, strlen($match[0])); },
$text
);
}
echo filterBadwords($text, $badwords);
Output is:
This is a test. ***. Grass. ****.