-1

I am trying to overwrite a line in PHP in a file if it contains a certain string. When I write to my file, the lines aren't overwritten but are appended to the end. I am opening the file as 'a+', not 'w+' as I don't want the settings of other 'modes' to be removed.

The file, for example:

mode1Hello= 100
mode1Goodbye= 200
mode1Neutral= 300
mode2Hello= 100
mode2Goodbye= 200
mode2Neutral= 300

I have tried:

$myfile = fopen("test.txt", "a+") or die("Unable to open file!");


    $lines = explode("\n", $myfile);
    $exclude = array();
    foreach ($lines as $line) {
        if (strpos($line, 'mode1') !== FALSE) {
             continue;
        }
        $exclude[] = $line;
    }
    echo implode("\n", $exclude);

$txt = "mode1Hello= 900\n";
fwrite($myfile, $txt);
$txt = "mode1Goodbye= 800\n";
fwrite($myfile, $txt);
$txt = "mode1=Neutral 700\n";
fwrite($myfile, $txt);

fclose($myfile);

But the test.txt file now reads:

mode1Hello= 100
mode1Goodbye= 200
mode1Neutral= 300
mode2Hello= 100
mode2Goodbye= 200
mode2Neutral= 300
mode1Hello= 900
mode1Goodbye= 800
mode1Neutral= 700

But I would like it to read:

mode1Hello= 900
mode1Goodbye= 800
mode1Neutral= 700
mode2Hello= 100
mode2Goodbye= 200
mode2Neutral= 300
DarkBee
  • 16,592
  • 6
  • 46
  • 58
Black Solis
  • 71
  • 1
  • 11
  • Trying to use `explode` on the file pointer resource returned by `fopen`, that makes no sense whatsoever. – CBroe Feb 16 '22 at 07:20
  • @CBroe open to suggestions good sir, if I knew how to do it I wouldn't be on here trying to learn PHP. – Black Solis Feb 16 '22 at 07:24
  • 4
    If memory serves, `a+` means 'all writes append'. You may want to try `r+`, which should allow you to overwrite as needed. However the best approach, in my opinion, is to read the entire file into memory , perform the string operations you need and then rewrite the entire file. – Refugnic Eternium Feb 16 '22 at 07:26
  • 1
    Does this answer your question? [Overwrite Line in File with PHP](https://stackoverflow.com/questions/235604/overwrite-line-in-file-with-php) https://stackoverflow.com/questions/235604/overwrite-line-in-file-with-php – Hendrik Feb 16 '22 at 07:48

1 Answers1

0
$filename = 'test.txt';

$contents = file_get_contents($filename);

$lines = explode("\n", $contents);

foreach ($lines as &$line) {
  if (str_starts_with($line, 'mode1Hello=')) {
    $line = 'mode1Hello= 900';
  } elseif (str_starts_with($line, 'mode1Goodbye=')) {
    $line = 'mode1Goodbye= 800';
  } elseif (str_starts_with($line, 'mode1Neutral=')) {
    $line = 'mode1Neutral= 700';
  }
}
unset($line);

$result = implode("\n", $lines);

file_put_contents($filename, $result);
lukas.j
  • 6,453
  • 2
  • 5
  • 24