Jump to content


Photo

Deleting data from a file on one line...


  • Please log in to reply
1 reply to this topic

#1 Janus13

Janus13
  • Members
  • PipPipPip
  • Advanced Member
  • 54 posts

Posted 11 October 2006 - 02:50 AM

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.

<?

$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);
?>
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

#2 Janus13

Janus13
  • Members
  • PipPipPip
  • Advanced Member
  • 54 posts

Posted 11 October 2006 - 04:08 AM

For those interested here is the solution:

	$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





0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users