我想在同一行中添加hello world


i want to add hello world in the same line

一种方法是使用file()函数。In返回特定文件每行内容的数组。从那里,您可以操作数组并将该值附加到特定的行上。考虑这个例子:

// 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
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

Array Splice Detail