PHP删除文本文件最后项后生成空白行的问题解决需求
PHP删除文本文件最后一项后残留空白行的问题解决
我用PHP操作文本文件删除数据时,删除最后一项后文件底部会多出一行空白行。统计文件行数时识别不到这行空白,导致删除操作会误删上一行,空白行却留着,影响后续代码迭代执行。
我把文件内容拆分到三个变量:
$start:存储文件起始部分(可能包含空白行)$changes:存储待删除的内容$rest:存储剩余内容
删除最后一项时,strlen($rest)的值为0。
核心写入代码:
$myfile = fopen("safe.txt", "w") or die("Unable to open file!"); fwrite($myfile, $start); fwrite($myfile, $rest);
完整操作代码:
$start = ""; $rest = ""; $myfile = fopen("safe.txt", "r") or die("Unable to open file!"); for ($i=0; $i<$line-1; $i++){ $start = $start.fgets($myfile); } $changes = ""; for ($i=0; $i<3; $i++){ $changes = $changes.fgets($myfile); } while(!feof($myfile)) { $rest = $rest.fgets($myfile); } fclose($myfile); $myfile = fopen("safe.txt", "w") or die("Unable to open file!"); fwrite($myfile, $start); if ($_POST["newName"]==0 AND $_POST["delete"]==0){ fwrite($myfile, $_POST["zname"]); fwrite($myfile, $space); fwrite($myfile, $_POST["zlocation"]); fwrite($myfile, $space); fwrite($myfile, $_POST["zsize"]); if (strlen($rest) > 0){ fwrite($myfile, $space); } } elseif ($_POST["newName"]==1 AND $_POST["delete"]==0){ fwrite($myfile, $_POST["zname2"]); fwrite($myfile, $space); fwrite($myfile, $_POST["zlocation"]); fwrite($myfile, $space); fwrite($myfile, $_POST["zsize"]); if (strlen($rest) > 0){ fwrite($myfile, $space); } } fwrite($myfile, $rest); fclose($myfile);
问题场景
当strlen($rest) == 0且$_POST["delete"] == 1时,文件内容从:
Name
Location
Size
Name 2
Location 2
Size 2
Name 3
Location 3
Size 3
变为:
Name
Location
Size
Name 2
Location 2
Size 2
尝试过用$start= str_replace("\n", '', $start);和preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $start);处理后写入,但问题没解决。
问题根源
fgets()会读取每行内容包括末尾的换行符,当删除最后一组3行内容时,$start的最后一行是Size 2\n,写入后就会在文件末尾留下一个空行。而统计行数时,这个空行因为只有换行符没有实际内容,可能不被计数,导致后续操作出错。
解决方法
在写入$start之前,针对$rest为空的删除场景,去除$start末尾的换行符:
$myfile = fopen("safe.txt", "w") or die("Unable to open file!"); // 处理删除最后一项且无剩余内容的情况 if ($_POST["delete"] == 1 && strlen($rest) == 0) { // 移除$start末尾的换行符(兼容Windows和Linux换行格式) $start = rtrim($start, "\r\n"); } fwrite($myfile, $start); fwrite($myfile, $rest);
额外优化建议
- 用
file()函数读取文件为数组,操作更直观,还能自动跳过空行:
$lines = file("safe.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); // 删除第$line到$line+2行(对应3行一组的内容) if (isset($lines[$line-1], $lines[$line], $lines[$line+1])) { array_splice($lines, $line-1, 3); } // 写入时自动添加换行,避免多余空行 file_put_contents("safe.txt", implode("\n", $lines) . "\n");
- 避免直接拼接字符串,改用数组存储内容再合并,减少换行符问题:
$startLines = []; for ($i=0; $i<$line-1; $i++){ $startLines[] = trim(fgets($myfile)); } // 后续写入时用implode("\n", $startLines)生成内容
内容的提问来源于stack exchange,提问作者littlelegs
相关产品推荐
相关产品推荐

