Website Scripts And Cloud Tutorials

Replace string in file using PHP

Byadmin

Mar 31, 2014

Last updated on May 19th, 2016 at 05:13 pm

Click to rate this tutorial!
[Total: 7 Average: 4]

Replace string in file using PHP

Once the file is replaced we can use PHP to save the file as well. A very simple example. Here test_file.php is the php file which contain an IP address (127.0.0.1) and I am going to replace that IP address from 127.0.0.1 to 127.1.9.9 , Once that is replace we are using fwrite() function in PHP to save the replaced file with the new IP address.

//read the entire string
$str=implode("",file('../test_file.php'));
$fp=fopen('../test_file.php','w');
//replace something in the file string, here i am replacing an IP address from  127.0.0.1 to 127.1.9.9
$str=str_replace('127.0.0.1','127.1.9.9',$str);
//now, save the file
fwrite($fp,$str,strlen($str));
Click to rate this tutorial!
[Total: 7 Average: 4]
2 thoughts on “Replace string in file using PHP”
  1. Nice little code! small and yet very efficient.
    However, it is missing a “fclose ($fp);”. and possibly a “clearstatcache();” as well.

Leave a Reply

Your email address will not be published.