Jump to: navigation, search

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

<?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


  1. PHP File Linux vs. Windows
  2. PHP File Information
  3. PHP File Create
  4. PHP File Close
  5. PHP File Read
  6. PHP File Read Reverse
  1. PHP File Write
  2. PHP File Write to end or append to
  3. PHP File Write at Beginning
  4. PHP File Write at specific location
  5. PHP File Truncate
  6. PHP File Replace a specific word
  1. PHP File Replace a specific word with associative array
  2. PHP File Copy File
  3. PHP File Copy Reverse
  4. PHP File Search within file
  5. PHP File Delete File
  6. PHP File Template
  1. PHP File Email Template
  2. PHP File Template with MySQL
  3. PHP File Access with MySQL
Navigation
Web
SQL
MISC
References