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

51 Views Asked by At

I am trying to delete set of lines on large text file using PHP. I am able to remove line set but its leaving blank line behind which I don't want. Kindly guide me how to do this with my existing codes. 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 after removing lines from 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>

Codes :

$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));
1

There are 1 best solutions below

0
AudioBubble On BEST ANSWER

instead of setting the value of the array key to blank, remove it from the array

so

$lines[$x] = '';

becomes

unset($lines[$x]);