簡體   English   中英

PHP用fgets替換文本文件頂部的行

[英]PHP replace line at the top of a text file with 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中的每一行都以分號結尾。

您將需要讀入整個文件以覆蓋該行,因為您描述的文件是一組非固定行(或者換句話說是一串字符)。 您將無法在不影響其他行字符的情況下原位替換大小不同的部分。

您不必一次將整個內容讀入內存。 fgets()方法使您一次只能讀取一行。 最少占用內存的方法是將所有值寫入新文件,然后刪除( unlink ())舊文件,然后rename()新文件rename()為舊文件名。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM