【问题标题】:How to insert string before last line?如何在最后一行之前插入字符串?
【发布时间】:2015-05-19 01:20:25
【问题描述】:

我看到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

【问题讨论】:

  • 你看过函数file()的文档吗?在“返回值”部分下,它明确指出:“数组的每个元素对应于文件中的一行,仍然附加换行符。”。您获得的额外行由implode(PHP_EOL, $arr) 添加。将空字符串 ('') 作为第一个参数传递给 implode(),多余的行将消失。

标签: php insert line


【解决方案1】:
$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);

【讨论】:

  • 我试过了,但永远循环 :( 并且在我的文本文件中聆听所有行
  • 我现在无法测试代码,因为我在手机上,但我编辑了代码。
  • 这很奇怪,这段代码对我有用。你确定你没有使用 splfileobject 就得到了更新的代码吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-04
  • 2021-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-11
相关资源
最近更新 更多