如何使用php从文本文件中删除一行而不留下空行 [英] How to remove a line from text file using php without leaving an empty line

查看:37
本文介绍了如何使用php从文本文件中删除一行而不留下空行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我可以使用 php 从文本文件中删除特定行.但是,删除该行后,会留下一个空行.无论如何,我是否可以删除该空行,以便后面的行可以向上移动?感谢您的帮助.

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.

推荐答案

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

这篇关于如何使用php从文本文件中删除一行而不留下空行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆