PHP File Replace a specific word with associative array
From w3cyberlearnings
Contents |
PHP File Replace Content use associative array
Replace a specific word within a file uses an associative array.
File Content (test1.txt)
a bad person make a bad world. a bad person loves to make trouble. a bad person mostly don't make a lot of problem.
Example 1
- Use str_replace() function.
<?php $file_name = 'test1.txt'; $str_replace = array('bad' => 'good', 'trouble' => 'peace'); // 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 with a list of string $new_file_content = str_replace(array_keys($str_replace), array_values($str_replace), $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
a good person make a good world. a good person loves to make peace. a good person mostly don't make a lot of problem.
Related Links
- PHP File Replace a specific word with associative array
- PHP File Copy File
- PHP File Copy Reverse
- PHP File Search within file
- PHP File Delete File
- PHP File Template