How to remove a line from a text file using php without leaving an empty line

Currently, I can remove a specific line from a text file using php. However, after deleting this line, an empty line will be left. Is there anyway for me deleting this empty line so that the lines behind can move up? Thank you for your help.

+3
php text-files
source share
3 answers
$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); 

it will just look at each line, and if this is not what you want to delete, it gets into an array that will be written back to the file.

+3
source share

Really? I find this muuuuch simpler, with only one line of code:

 file_put_contents($filename, str_replace($line . "\r\n", "", file_get_contents($filename))); 
+1
source share

You can improve this by setting the conditions for predicting 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); ?> 
0
source share

All Articles