Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Delete a line

Status
Not open for further replies.

qwicker

Programmer
Feb 16, 2005
12
0
0
US
Hello all,
I need a function to delete a line a line in a text file. I have this in my textfile:

text1 fdjkjflskdjf 0
text2 948yrxd74yrn 0
*text3 437nfy4837nf 0
text4 uhdwiueh92d9 0

I need to delete the entire line that begins with *text3. The numbers after *text3 are randomly generated(they are encrypted passwords), so i to delete the line based on "*text3" alone. How do i do that? My final file should look like this:

text1 fdjkjflskdjf 0
text2 948yrxd74yrn 0
text4 uhdwiueh92d9 0
 
read each line into an array, delete the offending array element and then write the revised array back to the file.

post if you would like help doing so. i have posted recently on very similar subjects and provided code.
 
I would much appreciate some help with this. I'm sure it isnt too complex, but im not exactly posetive how.

<?php
//open and read all the file
$filename = "/usr/local/something.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
 
given your structure i would use fgetcsv:

try the following code:

Code:
<?
error_reporting(E_ALL);
$filename =""; //filename here
$srchstring = "";//searchstring here
$delim = " ";//you are using space delimited. consider changing?
$lineend ="\n"; //new line character. change to suit your systme.
if (is_file($filename))
{
	$fh1 = fopen($filename, 'rb')  //the 'r' argument specifies that the file will be opened for read only b=binary
		or die ("cannot open file for read access");
}
else
{ 
	die("file does not exist");
}

//parse the first file
while ($var1[] = fgetcsv($fh1,1024,$delim)) //last parameter is th delimiter
{
 // bad coding but dont need to do anything
}
fclose($fh1); 
print_r ($var1);
//now have an array or arrays which need cleaning up for easy use
foreach ($var1 as $key=>$val)
{
	$data[$val[0]]=array("password"=>$val[1],"bool"=>$val[2]); //assume that field 0 (the text ident) is a unique key
}

//now rewrite the file

rename ($filename, "old_".rand(0,200). strtotime("now")."_".$filename); //backs up file
$fh1 = fopen($filename, 'wb');  //opens for write access. need binary for win systems

foreach($data as $key=>$val)
{
	if ($srchstring != $key && !empty($key))
	{
		fwrite($fh1, $key . $delim . $val['password'] . $delim . $val['bool'].$lineend);//doesnt write if the searchterm is matched or the array key is empty  - weird fgetcsv behaviour with some text files
	}
}
fclose($fh1);

?>
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top