Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove lines with no visible characters when reading a file

Tags:

file

php

Reading the official manual, if I want to skip empty line in a txt file, I just need to call the function file() with FILE_SKIP_EMPTY_LINES. I wrote:

$fileArray = file($uploadDirectory . $tracklistFile_name, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

but it also shows empty lines. So, in a text like this :

// START OF THE DOCUMENT
aaa
bbb

ccc
ddd

// END OF THE DOCUMENT

In fact sizeof($fileArray) is 6 : it adds the empty lines between bbb and ccc, and the last one. Why?

like image 753
markzzz Avatar asked Jan 26 '26 22:01

markzzz


2 Answers

There are a load of ways you could clean up the array but I like this one:

$fileArray = array_values(array_filter($fileArray, "trim"));
like image 61
James C Avatar answered Jan 29 '26 10:01

James C


FILE_SKIP_EMPTY_LINES really only skips empty lines. If you have spaces or tabs or other whitespace in it, file() will not consider it an empty line.

It doesn't do a trim before checking, it looks if $line=="\n" and only then considers it an empty line.


As alternative you could use:

$file = array_filter(array_map("trim", file("text.txt")), "strlen");
like image 26
mario Avatar answered Jan 29 '26 10:01

mario



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!