How can preg_replace be utilized in PHP to replace forbidden words in a text string?

To replace forbidden words in a text string using preg_replace in PHP, you can create an array of forbidden words and then use preg_replace with a regular expression pattern to replace those words with a replacement string. This allows you to easily filter out any unwanted language from a given text.

$forbiddenWords = array("badword1", "badword2", "badword3");
$text = "This is a text with badword1 and badword2 in it.";

$filteredText = preg_replace('/\b(' . implode('|', $forbiddenWords) . ')\b/i', '***', $text);

echo $filteredText;