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
- Are there any PHP libraries available that can handle extracting ID3 tags from song files to assist in determining song length?
- How can developers avoid potential pitfalls related to outdated PHP versions when using PHPMailer and other libraries?
- What are the advantages of server-side sorting in PHP compared to client-side sorting?