What are the best practices for replacing bad words in a string with good words in PHP?

To replace bad words in a string with good words in PHP, you can use the str_replace function. This function allows you to specify an array of bad words and an array of corresponding good words to replace them with. By looping through the arrays and replacing the bad words with the good words, you can effectively sanitize the string.

$badWords = array("bad1", "bad2", "bad3");
$goodWords = array("good1", "good2", "good3");

$string = "This is a string with bad1 and bad2 words.";

$newString = str_replace($badWords, $goodWords, $string);

echo $newString;