What best practices should be followed when replacing specific values in a PHP script, especially when dealing with file contents?

When replacing specific values in a PHP script, especially when dealing with file contents, it is important to ensure that the replacement is done accurately and securely. To achieve this, it is recommended to read the file contents, perform the necessary replacements using functions like `str_replace()`, and then write the modified contents back to the file.

<?php
$file_path = 'example.txt';

// Read the file contents
$file_contents = file_get_contents($file_path);

// Perform the replacements
$new_contents = str_replace('old_value', 'new_value', $file_contents);

// Write the modified contents back to the file
file_put_contents($file_path, $new_contents);
?>