I am deleting data from a text file however whenever I delete the last item in the file a blank line is created at the bottom of the file. I need to remove this blank line however when I count the number of lines in the file it isn't recognising the blank line as a line so anything I try to delete it deletes the line above it and I am left with a blank line still. I need to remove the blank line as it causes a new iteration to be ran later on in the code.
I read into three different variables $start, $changes and $ rest. $start contains the start lines of the file (may have the blank line) and $changes contains the stuff to be deleted and then $rest contains the rest of the file if it isn't the last item. When it is the last item strlen($rest) is 0.
The basic section of the code is as follows:
$myfile = fopen("safe.txt", "w") or die("Unable to open file!");
fwrite($myfile, $start);
fwrite($myfile, $rest);
The whole code containing all the if statements is below:
$start = "";
$rest = "";
$myfile = fopen("safe.txt", "r") or die("Unable to open file!");
for ($i=0; $i<$line-1; $i++){
$start = $start.fgets($myfile);
}
$changes = "";
for ($i=0; $i<3; $i++){
$changes = $changes.fgets($myfile);
}
while(!feof($myfile)) {
$rest = $rest.fgets($myfile);
}
fclose($myfile);
$myfile = fopen("safe.txt", "w") or die("Unable to open file!");
fwrite($myfile, $start);
if ($_POST["newName"]==0 AND $_POST["delete"]==0){
fwrite($myfile, $_POST["zname"]);
fwrite($myfile, $space);
fwrite($myfile, $_POST["zlocation"]);
fwrite($myfile, $space);
fwrite($myfile, $_POST["zsize"]);
if (strlen($rest) > 0){
fwrite($myfile, $space);
}
} elseif ($_POST["newName"]==1 AND $_POST["delete"]==0){
fwrite($myfile, $_POST["zname2"]);
fwrite($myfile, $space);
fwrite($myfile, $_POST["zlocation"]);
fwrite($myfile, $space);
fwrite($myfile, $_POST["zsize"]);
if (strlen($rest) > 0){
fwrite($myfile, $space);
}
}
fwrite($myfile, $rest);
fclose($myfile);
The issue occurs when strlen($rest) == 0 and $_POST["delete"] == 1 This causes the file to go from: " Name Location Size Name 2 Location 2 Size 2 Name 3 Location 3 Size 3"
To: " Name Location Size Name 2 Location 2 Size 2 "
I need to remove or stop that last line being written however i have tried removing the last line and i get:
" Name Location Size Name 2 Location 2 " I have also tried $start= str_replace("\n", '', $start); and preg_replace("/(^[\r\n]|[\r\n]+)[\s\t][\r\n]+/", "\n", $start); before writing it.