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