How can PHP developers efficiently replace bad words with asterisks in a given text file using PHP functions?

One efficient way for PHP developers to replace bad words with asterisks in a given text file is to read the file content, use the str_replace function to replace the bad words with asterisks, and then write the modified content back to the file. This can be achieved by opening the file in read and write mode, reading its content, replacing the bad words using str_replace, and then writing the modified content back to the file.

<?php
$bad_words = array("bad_word1", "bad_word2", "bad_word3");
$file_path = "path/to/your/file.txt";

$file_content = file_get_contents($file_path);

foreach ($bad_words as $bad_word) {
    $file_content = str_replace($bad_word, str_repeat("*", strlen($bad_word)), $file_content);
}

file_put_contents($file_path, $file_content);
?>