Bootstrap FreeKB - PHP - Replace file content
PHP - Replace file content

Updated:   |  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 Buy Me A Coffee



Comments


Add a Comment


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