Jump to content

Deleting data from a file on one line...


Janus13

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
Link to comment
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]
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

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.