How do I differentiate between an empty line and an endofline in PHP while reading character by character. In short I want to know how to find an empty line while reading char by char. Let me know if anything is unclear with a comment. Thank you...
Asked
Active
Viewed 96 times
1 Answers
1
You can either collect the characters of the current line in a buffer and then count when you see the end of line.
$buffer = '';
while (($char = fgetc($fp)) !== false) {
if ($char != '\n') {
$buffer .= $char;
} else {
if (strlen($buffer) == 0) {
echo "Empty line\n";
} else {
echo "Non-empty line\n";
}
$buffer = '';
}
}
Or you keep a count of characters while you read, until you see the end of line
$count = 0;
while (($char = fgetc($fp)) !== false) {
if ($char != '\n') {
++$count;
} else {
if ($count == 0) {
echo "Empty line\n";
} else {
echo "Non-empty line\n";
}
$count = 0;
}
}
As you can see, both versions are similar, it only depends on whether you need the line afterwards or not.
To consider \r
, you can compensate when you see one immediately before a \n
, e.g.
$cr = false;
$count = 0;
while (($char = fgetc($fp)) !== false) {
if ($char != '\n') {
$cr = false;
++$count;
if ($char == "\r")
$cr = true;
} else {
if ($cr)
--$count;
if ($count == 0) {
echo "Empty line\n";
} else {
echo "Non-empty line\n";
}
$count = 0;
}
}
$cr
is true, if the previous character was a \r
. So if you look at a newline and $cr
is true, you have a CRLF
and decrement the character count by one.
As an alternative, you can collect the whole line and trim whitespace before looking at the length
if (strlen(trim($buffer)) == 0) {
echo "Empty line\n";
} else {
echo "Non-empty line\n";
}
Even though not asked, reading a whole line and checking might be more efficient, e.g.
while (($buffer = fgets($fp)) !== false) {
if (strlen(rtrim($buffer, "\n")) == 0) {
echo "Empty line\n";
} else {
echo "Non-empty line\n";
}
}

Olaf Dietsche
- 72,253
- 8
- 102
- 198
-
Hello, Thank you @Olaf Dietsche... The problem I encountered is that every line has an \n char at the end whether it be in the form of a \r\n or a single \n. So searching for a \n while fgetc() is not being sufficient. So since in each line there is a \n I cannot differentiate between an empty line and an endof line. Can you follow my draft? Regards – Otag Nov 20 '16 at 18:03
-
I just found out that my solution also did not work. So I am still waiting for answers. Regards Otag – Otag Nov 20 '16 at 23:52
-
Hello @Olaf Dietsche. I will check and let you know with a correct answer mark. Thank you... – Otag Nov 21 '16 at 02:26
-
Hello @Olaf Dietsche ... Thank you for your miscellaneous solutions. I finally made one work => if (strlen(trim($buffer)) != 0).... else{ echo "empty line";} Thanks again Otag – Otag Nov 21 '16 at 03:33