PHP用fgets替换文本文件顶部的行

时间:2015-05-18 18:26:03

标签: php fopen fgets

我想用php打开一个文件并替换一条靠近顶部的行。由于它靠近顶部,我不想将整个文件读入内存。以下是我测试过的内容,但我认为一旦使用strpos()识别它,我就不会理解如何退出该行:

<?php

$file = "test-file.php";
$new_value = "colors:orange green violet;";
$fhandle = fopen($file, "r+") or die("Unable to open file!");
$replaced = "false";

while ($replaced === "false") {
    $line = fgets($fhandle);
        if (strpos($line, "colors:")) {   //find the colors line
        //Should I be moving the file pointer back here?
        //Once I find the line, how do I clear it?
        $line = $new_value;
        fputs($fhandle, $line);
        $replaced = "true";
    }
}
fclose($fhandle);
?>

test-file.php的内容:

 fruit:apples bananas;
 colors:red blue green;
 cars:ford chevy;

注意:test-file.php中的每一行都以分号结尾。

1 个答案:

答案 0 :(得分:0)

您需要读取整个文件,以覆盖该行,因为您描述的文件是一组非固定行(或另一种方式是字符流)。您将无法在不影响其他行中的字符的情况下替换其他大小的部分内容。

您不必一次性将所有内容都读入内存。 fgets()方法允许您一次只读一行。执行此操作的内存最少的方法是将所有值写入新文件,然后删除旧文件(unlink()),并将新文件rename()更新为旧文件名。

相关问题