How to replace text in a file using PHP

Home > Search > How-to
  by

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);

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter in the box below so that we can be sure you are a human.




Comments