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

时间:2015-05-18 15:27:16

标签: php insert line

我看到using fseek to insert string before last line这个问题,但这并不能解决我的问题。我不使用"?>"标签。 Php版PHP 5.4

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

我的代码正在运行,但这是在所有行之后添加空行:

  $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\n";
file_put_contents($filename, $person, FILE_APPEND);
$person = "andherelastline";
file_put_contents($filename, $person, FILE_APPEND);
//and then add again here

1 个答案:

答案 0 :(得分:5)

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