Open a text file, and remove line?

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
slipstream
Forum Commoner
Posts: 86
Joined: Fri Apr 19, 2002 8:53 am
Location: Canada

Open a text file, and remove line?

Post by slipstream »

Hi there I need some help on how to delete a line from a text file after I open it. The user will select a string to remove, then I have to open the file and find it and delete the line.

Can someone start me out here?
slipstream
Forum Commoner
Posts: 86
Joined: Fri Apr 19, 2002 8:53 am
Location: Canada

Post by slipstream »

no one can get me started?

I know I have to do a string compare as I read through each line of the file. Once it is found to be equal, how do I remove it is the Q?
User avatar
nielsene
DevNet Resident
Posts: 1834
Joined: Fri Aug 16, 2002 8:57 am
Location: Watertown, MA

Post by nielsene »

How about something like

Code: Select all

$testLine = $_POST["deleteMe"]; // or whereever it comes from
$file =file($filename); // stick the file into an array of lines
$fp = fopen($filename,"w"); // wipe the old file
$numlines = count($file);
for ($i=0;$i<$numlines;$i++)
  {
     if ($file[$i]!=$testLine)
       {
          fwrite($fp,$file[$i]);
        }
  }
fclose($fp);
edit: You'll probably have to add a \n to the fwrite. I'm not in a place I can test code right now.
slipstream
Forum Commoner
Posts: 86
Joined: Fri Apr 19, 2002 8:53 am
Location: Canada

Post by slipstream »

worked great, thanks.
User avatar
phice
Moderator
Posts: 1416
Joined: Sat Apr 20, 2002 3:14 pm
Location: Dallas, TX
Contact:

Post by phice »

Simply replace

Code: Select all

fwrite($fp,$file[$i]);
with

Code: Select all

fwrite($fp,$file[$i]."\n");
Image Image
Post Reply