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;
Keywords
Related Questions
- How can PHP developers troubleshoot and resolve issues related to unexpected changes or loss of session data, such as usernames being truncated or altered during user interactions within an application?
- How can the use of PHP functions like number_format and round enhance the readability and presentation of aggregated data from logfiles?
- What is the recommended approach for handling database connections in PHP classes?