Oberhaldenweg News Oberhaldenweg News - 1 month ago 17
PHP Question

PHP | Replace line in large txt-file

I have a large txt-file, for example:

text.txt
which contains:

line1
line2
line3
line4
line5
line6
line7
line8
line9


But I can't get any solotion how to make a PHP-file that simply replaces line
4
with the content
line4
with a different text....

Thank's for any help! :)

Answer

You should use PHP's file() function for that. It will return an array containing each line.

$file = file('path/to/text.txt');
$lines = array_map(function ($value) { return rtrim($value, PHP_EOL); }, $file);
$lines[3] = 'New content for line 4';
$lines = array_values($lines);

To save it again, implode the array with newline:

$content = implode(PHP_EOL, $lines);
file_put_contents('path/to/your/file.txt', $content);