What are the potential pitfalls of using preg_replace for filtering bad words in PHP scripts, and are there more efficient alternatives available?

Using preg_replace for filtering bad words in PHP scripts can be inefficient and prone to errors, as it relies on regular expressions that may not cover all variations of bad words. A more efficient alternative is to use an array of bad words and loop through each word to check and filter them in the input text. This method allows for more flexibility and accuracy in filtering out inappropriate language.

$badWords = array("badword1", "badword2", "badword3");
$inputText = "This is a sentence with badword1 and badword2.";

foreach($badWords as $word) {
    $inputText = str_ireplace($word, "***", $inputText);
}

echo $inputText;