PDA

View Full Version : Deleting only a certain line from a file, how??



shachi
08-20-2006, 02:22 PM
Can anyone tell me how do I delete a certain word from a file?? I was using this script found on http://php.net/file



$key = "test";
$fc=file("some.txt");
$f=fopen("some.txt","w");
foreach($fc as $line){
if (!strstr($line,$key))
fputs($f,$line);
}
fclose($f);
}


the problem with this code is it deletes all the lines related to the key. For e.g if the key is test it deletes test1 test2 test3 and every word that has the key.

I need a script that deletes only the exact key supplied.

Hope that makes sense.Any help would be appreciated. Thanks.

Twey
08-20-2006, 02:47 PM
If what is the exact key? The line? A word?

shachi
08-20-2006, 02:53 PM
Yes a word, something like usernames. The file will look something like this(words will be random, user entered):



test1
bla
bla345
shachi
twey
random word

Twey
08-20-2006, 04:07 PM
$file = 'some.txt';
$key = 'twey';

$lines = file($file);
for($i = 0; $i < count($lines); ++$i)
if(str_replace("\n", '', str_replace("\r\n", '', $lines[$i])) === $key)
$lines[$i] = '';
$f = fopen($file);
fwrite($f, implode('', $lines));
fclose($f);

shachi
08-20-2006, 04:40 PM
Twey, it is giving me warnings:




Warning: fopen() expects at least 2 parameters, 1 given in /opt/lampp/htdocs/myprojects/remline.php on line 9

Warning: fwrite(): supplied argument is not a valid stream resource in /opt/lampp/htdocs/myprojects/remline.php on line 10

Warning: fclose(): supplied argument is not a valid stream resource in /opt/lampp/htdocs/myprojects/remline.php on line 11



But nevermind I solved it myself.

Thanks for your help twey.:)

Twey
08-20-2006, 04:45 PM
Sorry, fopen($file, 'w');