Page 1 of 1

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

Posted: Thu Mar 13, 2008 7:59 pm
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

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

Posted: Fri Mar 14, 2008 4:55 am
by lambono
Any ideas? :banghead:

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

Posted: Fri Mar 14, 2008 5:32 am
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