Page 1 of 1
deleting a line from a file
Posted: Mon Dec 23, 2002 8:49 am
by graziano
Hello,
I have a user file user.php which contains following data
name1
name2
name3
name4
..
..
I am trying to write php code to open user.php , find "name2" (for example) , delete it , and save the file . Any idea to do that ?
thank you
Graz
Posted: Tue Dec 24, 2002 12:46 am
by graziano
please help ...
Posted: Tue Dec 24, 2002 12:56 am
by evilcoder
Try to explain it a bit better, i've read over and over, but i'm not quite getting it. Tell me exactly what you want to happen.
thanks
Posted: Tue Dec 24, 2002 2:50 am
by EricS
Here is one way to attack this.
Open the file in read mode.
Read each line and check to see if its the line you're looking for. If it's not, append it to an array. Repeat this till you get through the entire file.
Close the file.
Create a new file with the same name and send the contents of the array to the file and it will over write the old one.
Close the new file.
That's probably the long and slow way but it's late and I'm tired.
deleting a line from a file
Posted: Tue Dec 24, 2002 3:13 am
by JP
Hi,
I've solve the problem by converting the textfile into an array.
(image gallery app @
http://xywel.net/CLOSE_ENCOUNTERS/)
You need to use a uniq separator character such as CR/LF (line end

)
to be able to split the file content into array elements:
My file looks like:
filename_a.jpg
TAB some description of this image
CRLF
filename_z.jpg
TAB some description of this image
CRLF
which I split via:
Code: Select all
$content_array = spliti("ї\t]+|ї\n]+",$file_content);
This can be converted into an associative array, using filenames as a keys:
Code: Select all
$counter = 0;
while($counter < sizeof($content_array))
{
$descriptionsї$content_arrayї$counter]] = $content_arrayї$counter+1];
$counter = $counter + 2;
}
Delete an array element via:
Code: Select all
unset ($descriptionsї$key]);
Then rewrite the array as a file:
Code: Select all
fwrite($file_handle,$key."\t".$value."\n");
oh yeah chop the last \n on the last array element...
Cheers,
JP
Posted: Tue Dec 24, 2002 3:20 am
by evilcoder
nice. even i learnt something then. Well, thats not hard, i forget things as soon as i learn them. hahaha.
Posted: Fri Dec 27, 2002 1:48 pm
by graziano
Thanks a lot !