Rene Nikolay
Rene Nikolay

Reputation: 47

PHP remove last empty line in a textfile

I have a problem with a textfile. I have a textfile with an empty line (always the last line is empty). I need to remove this line. I tried several ways. Here is my current way to delete empty lines:

function RemoveEmptyLines($filename)
{
    $myfile = fopen($filename, "r") or die("Unable to open file!");
    $Content = fread($myfile,filesize($filename));
    fclose($myfile);
    $NewContent = preg_replace('/^\s+/m', '', $Content);
    $myfile2 = fopen('new.txt', "w") or die("Unable to open file!");
    fwrite($myfile2, $NewContent);
    fclose($myfile2);
    echo "removed";
}

This deletes all the empty lines within the textfile, but not the last empty line. If the content is:

1 \n 2 \n \n 3

It deletes the empty line. If it is:

1 \n 2 \n 3 \n \n

It doesn´t.. Any solutions? The problem is, that the file is dynamic, so I can´t just delete the last line, because it´s not always empty..

Upvotes: 2

Views: 2637

Answers (2)

AbraCadaver
AbraCadaver

Reputation: 78994

Get the contents, trim the end and put the contents:

file_put_contents($filename, rtrim(file_get_contents($filename));

Or, for your existing code, you don't want m (PCRE_MULTILINE) and you want to match the end of the string $. I think this pattern will work:

/\s+$/

Both solutions will removes spaces as well. If you don't want that:

/[\n\r]+$/

If you really want to delete ALL empty lines then you can read the file into an array, ignoring empty lines and put the contents back:

file_put_contents($filename, file($filename, FILE_SKIP_EMPTY_LINES));

However, if you are creating this file you might want to look at that code and not add the newline in the first place.

Upvotes: 4

stevie-c91
stevie-c91

Reputation: 98

Have you tried rtrim? Might be what you need:

rtrim($NewContent);

Upvotes: 2

Related Questions