【问题标题】:How to remove a line from text file using php without leaving an empty line [duplicate]如何使用PHP从文本文件中删除一行,而不会留下空线[复制]
【发布时间】:2011-11-19 22:52:50
【问题描述】:

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

【问题讨论】:

  • 您能告诉我们您目前使用的方法,以便我们有一个改进的起点吗?
  • 你在使用fopen()吗?知道这可能会有所帮助...

标签: php text-files


【解决方案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);  

这只会查看每一行,如果它不是你想要删除的,它会被推送到一个数组中,该数组将被写回到文件中。

【讨论】:

    【解决方案2】:

    真的吗?我发现这更容易,只有一行代码:

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

    【讨论】:

      【解决方案3】:

      您可以通过设置条件来预测错误来改进这一点。

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

      【讨论】:

        猜你喜欢
        • 2015-04-11
        • 2011-12-29
        • 1970-01-01
        • 1970-01-01
        • 2018-09-18
        • 1970-01-01
        • 2021-03-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多