【问题标题】:Replacing lines in a file does not remove empty lines替换文件中的行不会删除空行
【发布时间】:2019-01-04 19:21:20
【问题描述】:

我有这个函数可以从 txt 文件中删除行:

function replace_file($path, $string, $replace)
    {
        set_time_limit(0);

        if (is_file($path) === true)
        {
            $file = fopen($path, 'r');
            $temp = tempnam('./', 'tmp');

            if (is_resource($file) === true)
            {
                while (feof($file) === false)
                {
                    file_put_contents($temp, str_replace($string, $replace, fgets($file)), FILE_APPEND);
                }

                fclose($file);
            }

            unlink($path);
        }

        return rename($temp, $path);
    }

用法:replace_file("file.txt", "line to remove", '');

它运行良好,但它总是在文件末尾保留一个空行。

有办法解决吗?

任何帮助将不胜感激。

谢谢!

【问题讨论】:

  • 在文件末尾留空行通常被认为是正确的。 stackoverflow.com/a/2287990/2562137
  • 如果您只处理小文件,那么使用file() 和array walk 然后内爆到一个文件中的效果是一样的,但是对于大文件和小文件来说,一个更优化的解决方案是@987654323 @,您无法像使用 FILE_APPEND 一样解决当前代码的问题,并且不知道它是否是修剪新行的最后一行。
  • @Sarcoma 为什么会这样? (从技术上讲)。当我遇到它时,我总是将其移除;想知道我是否应该停下来,哈哈。
  • @J.ScottElblein 这是旧系统的遗留问题,旧系统期望在 EOF 之前有一个空行。在 PHP 中,它是 PSR-2 的一部分。
  • set_time_limit(0) 在函数调用中将其设置为零是一个非常糟糕的主意。函数不应该有这样的副作用。

标签: php


【解决方案1】:

我已经将函数编辑成这样:

function replace_file($path, $string, $replace)
    {
        set_time_limit(0);

        if (is_file($path) === true)
        {
            $file = fopen($path, 'r');
            $temp = tempnam('./', 'tmp');

            if (is_resource($file) === true)
            {
                while (feof($file) === false)
                {
                    file_put_contents($temp, str_replace($string, $replace, fgets($file)), FILE_APPEND);
                    file_put_contents($temp,
                        implode('', file($path, FILE_SKIP_EMPTY_LINES)));
                }

                fclose($file);
            }

            unlink($path);
        }

        return rename($temp, $path);
    }

现在它可以工作了。

【讨论】:

    【解决方案2】:

    如果您只想删除最后的空行,请查看rtrim

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-04
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-27
      相关资源
      最近更新 更多