在特定行之后将字符串添加到文件

时间:2014-06-09 13:12:50

标签: php string file

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

file_put_contents

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

4 个答案:

答案 0 :(得分:4)

已经很长时间,但对将来遇到此事的任何人都有用...

$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);

答案 1 :(得分: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

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

答案 2 :(得分:0)

另一种方法是使用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 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

答案 3 :(得分:-1)

以下是我的代码

 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),然后插入新行