What are the best practices for using str_replace in PHP to replace specific text in a file?

When using str_replace in PHP to replace specific text in a file, it is important to first read the contents of the file into a variable, perform the replacement using str_replace, and then write the modified contents back to the file. It is also recommended to use file_get_contents and file_put_contents functions for reading and writing files, as they provide a simpler and more efficient way to handle file operations.

// Read the contents of the file into a variable
$file = 'example.txt';
$content = file_get_contents($file);

// Perform the replacement using str_replace
$old_text = 'old_text';
$new_text = 'new_text';
$updated_content = str_replace($old_text, $new_text, $content);

// Write the modified contents back to the file
file_put_contents($file, $updated_content);