currently I am able to remove a specific line from text file using php. However, after removing that line, there will be an empty line left behind. Is there anyway for me to remove that empty line so that the lines behind can move up? Thank you for your help.
Asked
Active
Viewed 1.6k times
3
-
Can you show us the method you are currently using, so we can have a starting point to improve upon please? – jsnfwlr Sep 19 '11 at 04:24
-
Are you using `fopen()`? Knowing that might help... – alex Sep 19 '11 at 04:25
3 Answers
3
$DELETE = "the_line_you_want_to_delete";
$data = file("./foo.txt");
$out = array();
foreach($data as $line) {
if(trim($line) != $DELETE) {
$out[] = $line;
}
}
$fp = fopen("./foo.txt", "w+");
flock($fp, LOCK_EX);
foreach($out as $line) {
fwrite($fp, $line);
}
flock($fp, LOCK_UN);
fclose($fp);
this will just look over every line and if it not what you want to delete, it gets pushed to an array that will get written back to the file.

Thusitha Sumanadasa
- 1,669
- 2
- 22
- 30
1
Really? I find this muuuuch easier, only one line of code:
file_put_contents($filename, str_replace($line . "\r\n", "", file_get_contents($filename)));
0
You can improve this by setting conditions to predict errors.
<?PHP
$file = "a.txt";
$line = 3-1;
$array = file($file);
unset($array[$line]);
$fp = fopen($file, 'w+');
foreach($array as $line)
fwrite($fp,$line);
fclose($fp);
?>

Melsi
- 1,462
- 1
- 15
- 21