Jump to content

Archived

This topic is now archived and is closed to further replies.

Janus13

Deleting data from a file on one line...

Recommended Posts

I'm trying to figure out how to remove part of a line out of a file using PHP.  I use the following function for removing a line of data.

[code]
<?

$key = "data_to_remove";
$file = "groupfile"
$fc=file($file);
$f=fopen($file,"w");

foreach($fc as $line)
{
    if (!strstr($line,$key))
          fputs($f,$line);
}
fclose($f);
?>
[/code]
Of course this works great for removing information one line at a time, but in this case the file is one line, each entry separated by a space - so my question is how to remove part of a line while retaining the rest of it.  I should be able to read each part of the line into an array and have it not write the one I dont want, but I can't get my mind around the correct syntax.  Any help is appreciated!!

Jon

Share this post


Link to post
Share on other sites
For those interested here is the solution:

[code]
$user = "data_to_remove";
$groupfile = "file_to_remove_info_from";

$fc=file($groupfile); // Reads file contents into file
$f=fopen($groupfile,"w"); // Opens file and removes all contents
foreach ($fc as $line)  // reach each line in the array into an exploded array or each word
{
$line = rtrim($line);
$words = explode(" ",$line); 
}

foreach($words as $word) // for each word compre it and if it fits the user to remove dont put it in the file, otherwise put the user back in the file.
{
if(!strstr($word, $user))
{
fputs($f, $word . " ");
echo $word . " ";
}
}
fclose($f); // close the file
[/code]

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.