Replace string in file using PHP
Replace string in file using PHP
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));Replace string in file using PHP,
Nice little code! small and yet very efficient.
However, it is missing a “fclose ($fp);”. and possibly a “clearstatcache();” as well.
Thanks Philippe 🙂