Jump to: navigation, search

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


  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