search for blank line from text file

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
prue_
Forum Commoner
Posts: 64
Joined: Thu May 07, 2009 10:34 pm

search for blank line from text file

Post by prue_ »

hi, can someone give me an idea about this?
I want to search for blank line.. the code I created read data from text file line by line using fgets.. I want to show the text "Not available" if there's a blank line... I tried the ff:

Code: Select all

if (empty($variable))
if ($variable==NULL)
if ($variable =="")
if ($variable =="\r\n")
 
NULL and "" don't work

though if ($variable =="\r\n") and if (empty($variable)) works, it replaces everything because all data have spaces, tabs, etc..... what if i only want to read "blank line" only?? (between name 3 and name 4)
(e.g. from text file)
name1
name2
name3

name4

can you give me an idea on this? thanks in advance.... any idea will be very much appreciated
AlanG
Forum Contributor
Posts: 136
Joined: Wed Jun 10, 2009 1:03 am

Re: search for blank line from text file

Post by AlanG »

Now if you have a look at the file function it will read in each line of a file and assign them to an array. So if you loop through the array and use the empty function on it's contents, you will find an empty line.

Code: Select all

<?php
$lines = file('yourfile.txt');
$lines = array_map('trim',$lines); // Uses the trim function on each element to remove unwanted whitespace
 
foreach($lines as $line) {
    if(empty($line)) {
        echo 'Not Available';
    }
    else {
        echo $line;
    }
}
?>
That will show it on your screen, but from the wording on your post I'm not sure if you want to actually replace the empty lines in the text file with "Not Available"; If you do, the following code will work.

Code: Select all

<?php
$lines = file('yourfile.txt');
$lines = array_map('trim',$lines); // Uses the trim function on each element to remove unwanted whitespace
 
// This searches through each element of the array and replaces any empty elements with "Not Available"
foreach($lines as $key=>$value) {
    if(empty($line)) {
        $lines[$key] = 'Not Available';
    }
}
 
// We need to rewrite the array so we can place it in our file
$file_str = '';
foreach($lines as $line) {
    $file_str .= $line . "\r\n";
}
 
// Now we write it to the file (this will overwrite any content in the file specified)
$fh = fopen('yourfile.txt','w');
fwrite($fh,$file_str);
fclose($fh);
?>
prue_
Forum Commoner
Posts: 64
Joined: Thu May 07, 2009 10:34 pm

Re: search for blank line from text file

Post by prue_ »

hey, thanks AlanG... I didn't use your code, but I got your idea of trim.. thanks a lot.. you have no idea how you've helped me.. God bless you more!
Post Reply