What are the best practices for handling bad words in a PHP string using str_replace()?

When handling bad words in a PHP string, one common approach is to use the str_replace() function to replace these words with a placeholder or remove them entirely. To do this, create an array of bad words and their corresponding replacements, then use str_replace() to replace them in the string. This method allows for easy customization and scalability when filtering out inappropriate language from user input.

// Array of bad words and their replacements
$badWords = array("badword1", "badword2");
$replacement = "****";

// Input string
$inputString = "This is a string with badword1 and badword2.";

// Replace bad words with placeholder
$filteredString = str_replace($badWords, $replacement, $inputString);

// Output filtered string
echo $filteredString;