-2
片道はfile()
の機能を使用することです。 Inは、特定のファイルの内容を1行にまとめた配列を返します。そこから、配列を操作して、その特定の行にその値を追加することができます。この例を考えてみましょう:私は同じ行にこんにちはの世界を追加したい
// Sample file content (original)
// line 1
// line 2
// line 3
// line 4
// line 5
// line 6
$replacement = "Hello World";
$specific_line = 3; // sample value should be printed on this line
$contents = file('file.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
if($specific_line > sizeof($contents)) {
$specific_line = sizeof($contents) + 1;
}
array_splice($contents, $specific_line-1, 0, array($replacement)); // arrays start at zero index
$contents = implode("\n", $contents);
file_put_contents('file.txt', $contents);
// Sample output is this
// line 1
// line 2
// Hello World
// line 3
// line 4
// line 5
// line 6
// but Sample output should be
// line 1
// line 2
// line 3 Hello World
// line 4
// line 5
// line 6