我想知道是否有一种方法可以在特定行后将字符串添加到文件中在php中?我试过了
file_put_contents
,但它把字符串放在文件的末尾。谢谢你的帮助。
已经有很长一段时间了,但对于将来遇到这种情况的任何人都很有用…
$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);
这是一种方法,有点冗长,但使所有修改都内联:
$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
如果文件特别大,则需要一个中间文件
还有一种方法是使用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
下面是我的代码
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
),之后将插入新行