Page 1 of 1
Beginner Question: PHP detect empty line
Posted: Thu May 21, 2009 8:54 pm
by techjosh
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)
Code: Select all
do{
$temp = fgets($file);
if($temp != "\n")
$cap = $cap . $temp . "<br/>";
}while($temp != "\n");
Re: Beginner Question: PHP detect empty line
Posted: Thu May 21, 2009 9:44 pm
by Christopher
Code: Select all
do{
$temp = fgets($file);
if($temp != "") {
$cap = $cap . $temp . "<br/>";
}
}while($temp != "\n");
You can also do:
Code: Select all
while (file($path) as $line) {
if($line != '') {
$cap .= $line . '<br/>';
}
}
You might want to try echo()'ing out values you get to see what they contain.
Re: Beginner Question: PHP detect empty line
Posted: Thu May 21, 2009 11:23 pm
by requinix
Just a couple corrections there:
- fgets will include the newline in the returned string
- should be using a foreach instead of a while
Try running each line through
trim before checking if it's empty (with an empty string that is).
Re: Beginner Question: PHP detect empty line
Posted: Thu May 21, 2009 11:53 pm
by techjosh
Tried em both and couldn't get them to work. I figured I could simplify the whole process tho. Instead of planning on multiple lines of input per paragraph, my function that writes to the file will force every paragraph to be on one line. Then its just one fgets() per paragraph. Thx for trying tho.
Re: Beginner Question: PHP detect empty line
Posted: Fri May 22, 2009 12:36 am
by Scriptor
try strpos($string,"\n");
Re: Beginner Question: PHP detect empty line
Posted: Fri May 22, 2009 12:47 pm
by techjosh
Thank you all for your help. I used pieces from everyone's post and eventually got the thing fully working. Had to get a bit nuts and include the functions substr() and strlen()
Re: Beginner Question: PHP detect empty line
Posted: Fri May 22, 2009 2:03 pm
by Christopher
I think tasairis' suggestion is probably the best. Probably the way to do it is:
Code: Select all
$path = '/path/to/my/file.txt';
$cap = '';
while (file($path) as $line) {
if (trim($line) != '') {
$cap .= $line . '<br/>';
}
}