PHP File Replace Content
From w3cyberlearnings
Contents |
PHP Replace File Content
Replace a specific word within a file with a new one.
File Content(test1.txt)
A peaceful school makes a peaceful student A peaceful person makes a peaceful heart. A peaceful heart A peaceful world A peaceful person A peaceful community
Example 1
<?php $file_name = 'test1.txt'; // open file for reading only $file_handler_1 = fopen($file_name, 'r') or exit('can not open file!'); // store the file content into $file_content_1 $file_content_1 = fread($file_handler_1, filesize($file_name)); // replace file content $new_file_content = str_replace('peaceful', 'wonderful', $file_content_1); // close file fclose($file_handler_1); $file_handler_2 = fopen($file_name, 'w+') or exit('can not open file!'); if (fwrite($file_handler_2, $new_file_content)) { echo 'successfully write to the file<br/>'; } else { echo 'can not write to the file<br/>'; } fclose($file_handler_2); ?>
Output
- Replace the peaceful with wonderful.
A wonderful school makes a wonderful student A wonderful person makes a wonderful heart. A wonderful heart A wonderful world A wonderful person A wonderful community
Related Links
- PHP File Write
- PHP File Write to end or append to
- PHP File Write at Beginning
- PHP File Write at specific location
- PHP File Truncate
- PHP File Replace a specific word