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