What is the best practice for storing and retrieving bad words for a filter in PHP?
When creating a filter to detect and block bad words in PHP, it is best practice to store the list of bad words in a separate file or database for easy maintenance and retrieval. One approach is to store the bad words in a text file, read the file into an array in PHP, and then use this array to check against input text for bad words.
// Read bad words from a text file into an array
$badWords = file('bad_words.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
// Function to check if a given string contains any bad words
function hasBadWords($input, $badWords) {
foreach ($badWords as $word) {
if (stripos($input, $word) !== false) {
return true;
}
}
return false;
}
// Example usage
$inputText = "This is a test sentence with a bad word.";
if (hasBadWords($inputText, $badWords)) {
echo "Bad words detected!";
} else {
echo "No bad words found.";
}
Related Questions
- What potential issues can arise when handling HTTP responses in PHP, specifically in relation to character encoding?
- Is there a difference in PHP interpretation between accessing a website on the local server and accessing it remotely?
- What potential pitfalls should be considered when creating folders with PHP scripts?