How to delete a line from the file with php?

后端 未结 9 1471
北荒
北荒 2020-11-27 19:36

I have a file named $dir and a string named $line, I know that this string is a complete line of that file but I don\'t know its line number and I

9条回答
  •  温柔的废话
    2020-11-27 20:17

    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. see this

     $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);  
    

提交回复
热议问题