parse txt file to remove 1 line based on #id....?

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
lambono
Forum Newbie
Posts: 3
Joined: Thu Mar 13, 2008 7:53 pm

parse txt file to remove 1 line based on #id....?

Post by lambono »

Hi,
I hope someone can help me with this. Im stuck.

I have a text file in the following format

Code: Select all

 
#1
some information on a single line for id 1
 
#2
some information on a single line for id 2
 
#3
some information on a single line for id 3
 
#4
some information on a single line for id 4
 
etc.
 
How could I go about writing a function that would accept an id value and use this to remove the information for that id.

ie. parseFile(3) would change the text file to

Code: Select all

 
#1
some information on a single line for id 1
 
#2
some information on a single line for id 2
 
#4
some information on a single line for id 4
 
Thank you very much for your help!

Lambono
lambono
Forum Newbie
Posts: 3
Joined: Thu Mar 13, 2008 7:53 pm

Re: parse txt file to remove 1 line based on #id....?

Post by lambono »

Any ideas? :banghead:
lambono
Forum Newbie
Posts: 3
Joined: Thu Mar 13, 2008 7:53 pm

Re: parse txt file to remove 1 line based on #id....?

Post by lambono »

I managed to come up with this...

Code: Select all

 
<?php
 
$id=298;
 
copy("filename","filename.tmp");
 
$lines = file( "filename.tmp" );
 
$myFile = "filename";
 
$fh = fopen($myFile, 'w') or die("can't open file");
 
for( $i = 0; $i < sizeof($lines); $i++ )
{
    if (preg_match("/#$id/", $lines[$i]) )
        {
            $i=$i+2;
        }
    else
    {
        fwrite($fh, $lines[$i]);
    }
}
 
fclose($fh);
 
unlink("filename.tmp");
?>
Is there a better way to do this
Post Reply