一种方法是使用file()
功能。返回每行返回该特定文件的内容数组。从那里,您可以操作数组并将该值附加到该特定行。考虑这个例子:
// 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
答案 0 :(得分:0)
array_splice($contents, $specific_line-1, 0, array($replacement));
用
替换这个array_splice($contents, $specific_line-1, 1, array($contents[$specific_line-1].$replacement)); // arrays start at zero index