dtwy2858 2015-05-18 15:27
浏览 159
已采纳

如何在最后一行之前插入字符串?

I saw using fseek to insert string before last line this question, but this isn't solving my problem. I not use "?>" tag. Php version PHP 5.4

example line1
example line2
//i need insert here
lastline $eg};

My code is working but this is adding empty lines after all lines :

  $filename = 'example.php';   
  $arr = file($filename);
  if ($arr === false) {
      die('Error' . $filename);
    }
array_pop($arr);
file_put_contents($filename, implode(PHP_EOL, $arr));
/// I'm deleting last line here


$person = "my text here
";
file_put_contents($filename, $person, FILE_APPEND);
$person = "andherelastline";
file_put_contents($filename, $person, FILE_APPEND);
//and then add again here
  • 写回答

1条回答 默认 最新

  • dongqiangse6623 2015-05-18 15:42
    关注
    $file = "tmp/saf.txt";
    $fc = fopen($file, "r");
    while (!feof($fc)) {
        $buffer = fgets($fc, 4096);
        $lines[] = $buffer;
    }
    
    fclose($fc);
    
    //open same file and use "w" to clear file 
    $f = fopen($file, "w") or die("couldn't open $file");
    
    $lineCount = count($lines);
    //loop through array writing the lines until the secondlast
    for ($i = 0; $i < $lineCount- 1; $i++) {
        fwrite($f, $lines[$i]);
    }
    fwrite($f, 'Your insert string here'.PHP_EOL);
    
    //write the last line
    fwrite($f, $lines[$lineCount-1]);
    fclose($f);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿