【问题标题】:add string to file after a specific line在特定行之后将字符串添加到文件
【发布时间】:2025-12-24 05:25:11
【问题描述】:

我想知道是否有一种方法可以在特定行之后将字符串添加到文件中 在 PHP 中? 我试过了

file_put_contents

但它将字符串放在文件的末尾。 感谢您的帮助。

【问题讨论】:

  • 使用file(),应该是数组格式,从那里使用键

标签: php string file


【解决方案1】:

已经很长时间了,但对以后遇到此问题的任何人都会有用...

$f = fopen("path/to/file", "r+");

$oldstr = file_get_contents("path/to/file");
$str_to_insert = "Write the string to insert here";
$specificLine = "Specify the line here";


// read lines with fgets() until you have reached the right one
//insert the line and than write in the file.


while (($buffer = fgets($f)) !== false) {
    if (strpos($buffer, $specificLine) !== false) {
        $pos = ftell($f); 
        $newstr = substr_replace($oldstr, $str_to_insert, $pos, 0);
        file_put_contents("path/to/file", $newstr);
        break;
    }
}
fclose($f);

【讨论】:

    【解决方案2】:

    这是一种方法,有点冗长,但所有修改都内联:

    $f = fopen("test.txt", "tr+");
    
    // read lines with fgets() until you have reached the right one
    
    $pos = ftell($f);                   // save current position
    $trailer = stream_get_contents($f); // read trailing data
    fseek($f, $pos);                    // go back
    ftruncate($f, $pos);                // truncate the file at current position
    fputs($f, "my strings\n");          // add line
    fwrite($f, $trailer);               // restore trailing data
    

    如果文件特别大,则需要一个中间文件。

    【讨论】:

      【解决方案3】:

      还有一种方法是使用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 squeeze it 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
      // line 1
      // line 2
      // Hello World
      // line 3
      // line 4
      // line 5
      // line 6
      

      【讨论】:

        【解决方案4】:

        以下是我的代码

         function doit($search,$file,$insert)
        {
        $array = explode("\n", file_get_contents($file));
        $max=count($array);
        for($a=0;$a<$max;$a++)
        {if($array[$a]==$search) {
        $array = array_slice($array, 0, $a+1, true) +
        array($insert) +
        array_slice($array, $a+1);
         break;}}
         $myfile = fopen($file, "w");
         $max=count($array);
         var str='';
         for($a=0;$a<$max;$a++)
         {str.=$array[$a].'\n';}
         fclose($myfile);
         }
        

        您必须提供文件路径 ($file)、新行文本 ($insert) 和要插入新行的行文本 ($search)

        【讨论】:

        • 最好用file()而不是explode(..., file_get_contents(...))