dou448172583 2018-07-02 03:59
浏览 166
已采纳

PHP如何从大文本文件中删除行集而不留空行

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("
", $lines));
  • 写回答

1条回答 默认 最新

  • duan6301 2018-07-02 04:09
    关注

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

    so

    $lines[$x] = '';
    

    becomes

    unset($lines[$x]);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?