這裏是基於gnarf's 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);
這將改變(替換)sample.txt
具有以下內容的示例:
line one
line two
line three
line four
line five
到
line one
line two
Here is the new value for the line 3line three
line four
line five
尋求()與工作「字節」偏移量,而不是行號。除非你使用已知的固定長度的線條(它可以讓你做一些數學來計算偏移應該是什麼),那麼你需要一次讀取每一行以獲得你想要的偏移量...... 。電腦不能奇蹟般地猜測線路長度可能純粹是任意的 –
非常感謝,@MarkBaker – Ali