我有这个函数可以从 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", '');
它工作得很好,但它总是在文件末尾保留一个空行。
有可能解决吗?
任何帮助,将不胜感激。
谢谢!