在處理文本文件時,有時需要在特定行、特定字符位置插入新內容。本文提供一個 PHP 函數 insertContent,實現按行號與字符索引精準插入字符串,並演示如何將修改後的內容寫回文件。
<?php
$arrInsert = insertContent("array.php", "abcdef", 3, 10);
unlink("array.php");
foreach($arrInsert as $value) {
file_put_contents("array.php", $value, FILE_APPEND);
}
function insertContent($source, $s, $iLine, $index) {
$file_handle = fopen($source, "r");
$i = 0;
$arr = array();
while (!feof($file_handle)) {
$line = fgets($file_handle);
++$i;
if ($i == $iLine) {
if($index == strlen($line)-1) {
$arr[] = substr($line, 0, strlen($line)-1) . $s . "\n";
} else {
$arr[] = substr($line, 0, $index) . $s . substr($line, $index);
}
} else {
$arr[] = $line;
}
}
fclose($file_handle);
return $arr;
}
?>
函數逐行讀取文件,當行號匹配時,根據 $index 將原行拆分為前後兩部分,中間插入新字符串;其他行保持不變。最後返回處理後的行數組,調用者可遍歷寫入文件。
適用於配置文件修改、日誌標記、模板佔位符替換等需精確控制插入位置的場景。注意:大文件建議使用流式處理以避免記憶體壓力。