How can str_replace be used effectively to replace specific content in a file in PHP?

To replace specific content in a file using str_replace in PHP, you can read the content of the file into a variable, use str_replace to replace the specific content, and then write the modified content back to the file.

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

$old_content = 'old content';
$new_content = 'new content';

$modified_content = str_replace($old_content, $new_content, $content);

file_put_contents($file_path, $modified_content);