What is the recommended method for replacing text in a file using PHP without affecting other values?

When replacing text in a file using PHP, it is important to ensure that only the targeted text is modified without affecting other values in the file. One way to achieve this is by reading the file contents, replacing the desired text using a regular expression or string manipulation, and then writing the modified contents back to the file.

<?php
// Specify the file path
$file = 'example.txt';

// Read the file contents
$content = file_get_contents($file);

// Replace the desired text
$updatedContent = str_replace('old_text', 'new_text', $content);

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