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

16,020
     $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.

Share:
16,020
Chloe MieMie Wang
Author by

Chloe MieMie Wang

Updated on June 04, 2022

Comments

  • Chloe MieMie Wang
    Chloe MieMie Wang almost 2 years

    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.