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

假如想象 提交于 2019-12-23 17:42:01

问题


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.


回答1:


     $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.




回答2:


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

file_put_contents($filename, str_replace($line . "\r\n", "", file_get_contents($filename)));



回答3:


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

?>


来源:https://stackoverflow.com/questions/7466424/how-to-remove-a-line-from-text-file-using-php-without-leaving-an-empty-line

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!