Re: Deleting a string from a text file

From: Date: Wed, 04 Jul 2001 02:32:59 +0000
Subject: Re: Deleting a string from a text file
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-56103@lists.php.net to get a copy of this message
On Tue, 3 Jul 2001 18:04, Stevenson, Christopher wrote: > Hello, folks. I'm relatively new to this. > > Would anyone be willing to give me some code that will delete the first > occurrence of a string from a text file? > > Thanks, > Chris. Hello Chris - when did you guys discover PHP! Grab the file into an array with file(), loop through the array and do a ereg or substr to find the string, str_replace to replace the string (with a counter to ensure you only do the first occurrence) then fopen the file, reset the array to the first element and loop throug the array writing each element back to the file. Code might look like this: $string_to_find = 'whatever'; $file = 'filename.txt'; //assuming its in CWD $data = file($file); //$data is an array with the file contents $changed = 0 // flag to indicate you've found a string to change while (list($key , $curr_line) = each($data)) { if(changed != 0) { break; //Already got first replacement - finish } if (substr($string_to_find, 0)) { str_replace($string_to_find, '', $curr_line); $changed = 1; } } //Now write data back to the file $file_pointer = fopen($file,"w"); //Open file for writing reset($data); //Set array pointer to first element / And loop throgh array writing each element (line) back to file while (list($key , $curr_line) = each($data)) { fwrite($file_pointer, $curr_line); } // Close the file nicely fclose(fpointer); That's just one way of doing it - I'm sure there will be other suggestions. And of course it depends on what's in the string you are trying to delete; you may have to ereg and ereg_replace. This code is untested, of course - the usual disclaimers apply. Cheers -- David Robley Techno-JoaT, Web Maintainer, Mail List Admin, etc CENTRE FOR INJURY STUDIES Flinders University, SOUTH AUSTRALIA The first step to making a dream come true is to wake up

« previous php.general (#56103) next »