Here is an example based on gnarf answer here
<?php $targetFile = './sample.txt'; $tempFile = './sample.txt.tmp'; $source = fopen($targetFile , 'r'); $target = fopen($tempFile, 'w'); $whichLine = 5; $whatToReplaceWith = 'Here is the new value for the line ' . $whichLine; $lineCounter = 0; while (!feof($source)) { if (++$lineCounter == $whichLine) { $lineToAddToTempFile = $whatToReplaceWith; } else { $lineToAddToTempFile = fgets($source); } fwrite($target, $lineToAddToTempFile); } unlink($targetFile); rename($tempFile, $targetFile);
which will change (replace) sample.txt with the following content:
line one line two line three line four line five
to
line one line two Here is the new value for the line 3line three line four line five
user5060359
source share