How can PHP beginners effectively utilize file() and foreach() functions to read and replace bad words in a text file within their scripts?
To read and replace bad words in a text file using PHP, beginners can utilize the file() function to read the contents of the file into an array, and then use the foreach() function to iterate through each line and replace any bad words with a desired replacement word.
$bad_words = ['bad_word1', 'bad_word2', 'bad_word3']; // List of bad words
$replacement_word = '***'; // Word to replace bad words with
$file_lines = file('text_file.txt'); // Read file into an array
foreach ($file_lines as $line) {
$cleaned_line = str_ireplace($bad_words, $replacement_word, $line); // Replace bad words with replacement word
echo $cleaned_line; // Output cleaned line
}