Jump to: navigation, search

PHP File Write at specific location

From w3cyberlearnings

Contents

PHP write to a specific line

Write or replace a new content to a specific line within a file.

File Content(test1.txt)

A peaceful school makes a paceful student
A peaceful person makes a peaceful heart.
A peaceful heart
A peaceful world
A peaceful person
A peaceful community

Example 1:replace

<?php

$file = 'test1.txt';
$line_looking = 4;

$lines = file($file, FILE_IGNORE_NEW_LINES);
$lines[$line_looking] = 'Please, no violence!';
file_put_contents($file, implode("\n", $lines));
?>

Output

  • Replace line 4 with Please, no violence!.
A peaceful school makes a paceful student
A peaceful person makes a peaceful heart.
A peaceful heart
A peaceful world
Please, no violence!
A peaceful community

Example 2: replace in a specific location

<?php

$file = 'test1.txt';
$line_looking = 4;

$lines = file($file, FILE_IGNORE_NEW_LINES);
$lines_tmp = array();

for ($i = 0; $i < count($lines); $i++) {
	if ($i == $line_looking) {
		$lines_tmp[] = 'Please of the word!!!!!';
		$lines_tmp[] = $lines[$i];
	} else {
		$lines_tmp[] = $lines[$i];
	}
}
file_put_contents($file, implode("\n", $lines_tmp));
?>

Output

A peaceful school makes a paceful student
A peaceful person makes a peaceful heart.
A peaceful heart
A peaceful world
Please of the word!!!!!
A peaceful person
A peaceful 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