PHP 如何在不留下空行的情况下从大文本文件中删除行集

PHP How to remove a line set from large text file without leaving an empty line

我正在尝试使用 PHP 删除大型文本文件中的一组行。我可以删除行集,但它会留下我不想要的空行。请指导我如何使用现有代码执行此操作。 My ref question

Example.txt :

MaxBytes[192.168.1.1]: 10000
 <TABLE>
   <TR><TD>IP Address:</TD><TD>192.168.1.1</TD></TR>
   <TR><TD>Max Speed:</TD> <TD>300</TD></TR>
 </TABLE>

MaxBytes[192.168.1.2]: 30000
 <TABLE>
   <TR><TD>IP Address:</TD><TD>192.168.1.2</TD></TR>
   <TR><TD>Max Speed:</TD> <TD>300</TD></TR>
 </TABLE>

MaxBytes[192.168.1.3]: 10000
 <TABLE>
   <TR><TD>IP Address:</TD><TD>192.168.1.3</TD></TR>
   <TR><TD>Max Speed:</TD> <TD>200</TD></TR>
 </TABLE>

Example.txt 从 php 中删除行后:

    MaxBytes[192.168.1.1]: 10000
 <TABLE>
   <TR><TD>IP Address:</TD><TD>192.168.1.1</TD></TR>
   <TR><TD>Max Speed:</TD> <TD>300</TD></TR>
 </TABLE>







MaxBytes[192.168.1.3]: 10000
 <TABLE>
   <TR><TD>IP Address:</TD><TD>192.168.1.3</TD></TR>
   <TR><TD>Max Speed:</TD> <TD>200</TD></TR>
 </TABLE>

代码:

$first = $line_number[0] -1; --> Getting first line of set from external source
$last = $line_number1[0] -1; --> Getting last line of set from external source


$lines = file($dir, FILE_IGNORE_NEW_LINES);
//$out = array();
for ($x = $first; $x <= $last; $x++) {
    echo "Line number to be delete : $x <br>";
    $lines[$x] = '';
}

//var_dump($lines);
file_put_contents($dir , implode("\n", $lines));

与其将数组键的值设置为空白,不如将其从数组中移除

所以

$lines[$x] = '';

变成

unset($lines[$x]);