0

我有这个函数可以从 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", '');

它工作得很好,但它总是在文件末尾保留一个空行。

有可能解决吗?

任何帮助,将不胜感激。

谢谢!

4

2 回答 2

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

现在它可以工作了。

于 2018-07-27T22:15:28.823 回答
1

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

于 2018-07-27T16:26:49.290 回答