PHP - Replace file content

by
Jeremy Canfield |
Updated: March 11 2020
| PHP articles
Let's say you have a file with a few lines of data.
John Smith 1979
Jane Smith 1984
Jack Jones 1975
Betty Jackson 2001
The following PHP will replace every instance of the string "Smith" with "Johnson" in the file. If the file is on Linux, the file may need 777 permission.
<?php
# Load the contents of example.txt into a variable called $myfile
$myfile = file_get_contents('example.txt');
# Replace every instance of Smith with Johnson
$replacement = str_replace("Smith", "Johnson", $myfile);
# Execute the replacement
file_put_contents('example.txt', $replacement);
?>
Executing the PHP should update the file to have the following content.
John Johnson 1979
Jane Johnson 1984
Jack Jones 1975
Betty Jackson 2001
The following can be used to do more than once replacement at the same time.
$replacement = str_replace(
array("Smith", "Johnson"),
array("Betty", "Susan),
$myfile);
Did you find this article helpful?
If so, consider buying me a coffee over at