Reputation: 141
I have the following test program:
#!/usr/bin/php
<?php
echo "Starting\n";
# Now read the file.
#
$file_pn = "contact.txt";
$fh = fopen($file_pn, 'r');
while (!feof($fh)) {
$line = fgets($fh);
$trimmed = trim($line);
echo "trimmed = <" . $trimmed . ">\n";
if (preg_match('/^\s*$/', $trimmed)) {
echo "Looks blank: trimmed = <" . $trimmed . ">\n";
#continue;
}
}
fclose($fh);
?>
The file being read has some blank lines and some non-blank lines. As shown here, it acts as one would expect: only the lines that are actually blank receive the "Looks blank" message, and trimmed = <>. But if I comment out the echo statement in line 12 and run the script again, $trimmed always appears to be the empty string when we get to the if statement. It is as if $trimmed gets clobbered unless it has been echoed. How can this be?
Upvotes: 2
Views: 65
Reputation: 2617
I don't think you need to be using a regex there. If the line is only whitespace to begin with, trim()
will make it empty.
Try:
if (empty($trimmed)) {
It behaves as expected for me - since you're now not echoing any lines that aren't empty, your output will only show a heap of empty lines
$ ./test|wc -l
18
$ nano test #comment line 12
$ ./test|wc -l
6
Upvotes: 2