Re: delete lines from text file

From: Date: Fri, 06 Jun 2003 05:59:26 +0000
Subject: Re: delete lines from text file
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-150451@lists.php.net to get a copy of this message
Matt, Try something like: <? $fp=fopen("file_name.txt","r"); while (feof($fp)) { $line=fget($fp,100); // grabs text to end of line or 100 characters whichever comes first if (!preg_match("/delete/",$line)) { $new_line.=$line; } } fclose($fp); $fp=fopen("file_name.txt","w"); fwrite($fp,$new_line) or die ("something died in here"); fclose($fp); ?> I didn't check this before posting so there could be some syntax issues, but the flow is what you need. Open a file for reading, read it line by line to find a text phrase, accumulate the lines (less the one with the phrase) in a new variable, close the file, open it again for writing, write the text to the file, and then close it. Hope this helps, Hugh ----- Original Message ----- From: "Matt Palermo" <mpalermo@vt.edu> To: <php-general@lists.php.net> Sent: Thursday, June 05, 2003 8:53 PM Subject: [PHP] delete lines from text file > Can anyone help me figure out how to search for a string in a text file, > then delete the whole line of text that it occurs in? > > For example: I have a text file which contains the following. > > //****** text.txt ****** > Keep this line. > Also keep this line. > Delete this line. > Keep this one too. > > > Now I want to do a search on this text file for the word "delete" and if > it finds that word, it will delete the whole line it occurs on. So > after this, the text file will look like this one: > > //****** text.txt ****** > Keep this line. > Also keep this line. > Keep this one too. > > Can anyone help me with this? Thanks. > > Matt >

« previous php.general (#150451) next »