How can the str_replace function be utilized to replace specific text in a file loaded using PHP?

To replace specific text in a file loaded using PHP, you can use the str_replace function. This function allows you to search for a specific string within a given text and replace it with another string. By loading the file contents into a variable, you can then use str_replace to make the desired changes to the text.

$file_path = 'example.txt';
$file_contents = file_get_contents($file_path);

// Replace 'old_text' with 'new_text' in the file contents
$updated_contents = str_replace('old_text', 'new_text', $file_contents);

// Write the updated contents back to the file
file_put_contents($file_path, $updated_contents);