Mike
Mike

Reputation: 419

Get last line of a file ignoring empty lines or whitespace

I have a file I'm parsing with PHP. It seems the contents of the file apparently end in a blank new line, sometimes with spaces. How can I trim this out and get the true last line ?

My file can sometimes look like

Line 1
Line 2
File content are here 
\n

or

Line 1
Line 2
File content are here 
\r

or sometimes the correct way

Line 1
Line 2
File content are here 

I need my script to parse the end of the file and return the true last line which is "File content here" (or anything really, just not a blank line).

I was using the line below to attempt to get the last line. The problem is, I don't always know what X is. And even if I do think I know, line breaks and empty lines at the end of the file are throwing me off.

fseek($file_handle, -X, SEEK_END);

Upvotes: 1

Views: 1211

Answers (1)

user2629998
user2629998

Reputation:

You may use the following approach which doesn't load the entire file in memory (you can process extremely large files with it) and allows to have empty lines anywhere in the file, instead of only at the end.

while (($line = fgets($file_handle)) !== false) {
    if (($line != "\n") && ($line != "\r")) {
        // line is correct, process it
    }
}

This code iterates over each line, then checks if the line isn't equal to \n nor \r and if that isn't the case it processes the line, otherwise it's silently discarded and the code skips to the next line.

You can also use the new SplFileObject interface introduced in PHP 5.1.0, the code is very similar and works the same way :

$file = new SplFileObject("file.txt");

while (!$file->eof()) {
    $line = $file->fgets();
    if (($line != "\n") && ($line != "\r")) {
        // line is correct, process it
    }
}

Also I overlooked the fact that you needed only the last line in the first revision of my answer; an easy solution would be to define a variable inside the loop if the line is correct (and not an empty/junk one), if there are lines after that the variable would just get overwritten, but it'll stay set on the last correct line and you can then do whatever you want with it.

while (($line = fgets($file_handle)) !== false) {
    if (($line != "\n") && ($line != "\r")) {
        $last = $line
    }
}

if (isset($last)) {
    echo "you've got your last line"
}

This may not be the best solution performance-wise but it's definitely the easiest, for better methods on getting the last line I refer you to this question that has quite long and complicated solutions that would need modifications if you want them to ignore empty lines.

Upvotes: 1

Related Questions