-2
один способ - 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