0

I'd like to use php to open a file and replace just one line that will be near the top. Since it's near the top I don't want to read the whole file into memory. Here is what I've tested but I think I am not understanding how to backspace over the line once I identify it using 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);
?>

Contents of test-file.php:

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

Note: Each line in test-file.php ends with a semicolon.

emailcooke
  • 271
  • 1
  • 4
  • 17
  • ``fgets()`` includes the newline char(s), so you probably want to run ``$line = trim(fgets($fhandle))`` or otherwise handle the new line before making string comparisons – fbas May 18 '15 at 18:33

1 Answers1

0

You will need to read the whole file in, in order to overwrite that line, because the file you describe is a set of non-fixed lines (or put another way is a stream of characters). You won't be able to replace a part of it in-place, of a different size, without affecting characters in other lines.

You don't have to read the whole thing into memory all at once. The fgets() approach lets you read just a line at a time. The least memory intensive way to do this is to write all values to a new file, then delete (unlink()) the old file, and rename() the new file to the old filename.

fbas
  • 1,676
  • 3
  • 16
  • 26