PDA

View Full Version : Easy quick question: PHP detect empty line



techjosh
05-21-2009, 02:26 PM
Hello. I'm finding this surprisingly confusing, and more surprising at how no one else seems to be confused by it.

In PHP I need to detect a line for a blank space using fgets(). I've tried using the following "\n" '\n' "\r\n" 'null' ' ' " " etc. and nothing seems to work

The following function is suppose to read a text file and set $cap to the paragraph in the text file until a blank line is read in the text file (the entire thing is in another loop to do it again for another paragraph until end of file)


do{
$temp = fgets($file);
if($temp != "\n")
$cap = $cap . $temp . "<br/>";
}while($temp != "\n");

JamesYap
06-01-2009, 01:38 PM
Since fgets() fetch a line at a time from the file pointer $file, each line will end at the line break which is '/n'. And that's why it is not included when you fetch an empty lines. What you need to do is simply to change

if($temp != "\n")

to

if(empty($temp))

which will be able to detect the empty line easily.

RedMatrix
06-09-2009, 09:55 AM
I agree with JamesYap. There is a difference between "empty" and "blank" lines. What happens if the "blank" line has a space, or a tab in it? (or more) Is it still blank, is it still empty?

I also like using trim() to remove the empty spaces before and after the content. If it is a line that appears to be blank to human eyes, this would delete all whitespace, and thus, assure it is indeed an empty line.

JenniC
06-15-2009, 08:58 AM
The lex command in biterscripting provides an option to distinguish between blank and empty lines.

lex -e will give you an empty line (without anything). lex will give you a non-empty line. The regular expression ";" then can check if a line has nothing but non-printable characters (space, tab, etc.)

You can try by installing from http://www.biterscripting.com/install.html and see if that serves your purpose. It tends to save a lot of customized programming.

J