问题描述
我有一个文本文件,更多有关程序的用户文件.我正在尝试使用PHP在文件中的group:之前插入新数据.最后一位用户在此行上方,我想在该用户下方和组上方插入新用户:
I have a text file, more of a users file for a program. Im trying to use PHP to insert new data before groups: in the file. The last user is above this line and i want to insert new users below the last user and above groups: in the file
我一直在做些小尝试,但是我只能在那行之后得到它.
Ive been tinkering and was trying some things, but i can only get it after that line.
这就是我所拥有的
$key = 'groups:';
$newline = 'blackberry';
//copy file to prevent double entry
$file = "data2.yml";
$newfile = "filetemp.txt";
copy($file, $newfile) or exit("failed to copy $file");
//load file into $lines array
$fc = fopen ($file, "r");
while (!feof ($fc))
{
$buffer = fgets($fc, 4096);
$lines[] = $buffer;
}
fclose ($fc);
//open same file and use "w" to clear file
$f=fopen($newfile,"w") or die("couldn't open $file");
/* uncomment to debug */
print_r($lines);
print "
\n";
//loop through array using foreach
foreach($lines as $line)
{
fwrite($f,$line); //place $line back in file
if (strstr($line,$key)){ //look for $key in each line
fwrite($f,$newline."\n");
} //place $line back in file
}
fclose($f);
copy($newfile, $file) or exit("failed to copy $newfile");
?>
它是一个yml文件,因此我无法在之后添加额外的行来发布,否则它会拧紧并拒绝运行.
Its a yml file, so i cant add an extra line to post after or it screws up and refuses to run.
谢谢!
推荐答案
您的foreach代码应为:
your foreach code should be:
foreach($lines as $line)
{
if (strstr($line,$key)){ //look for $key in each line
fwrite($f,$newline."\n"); //insert data before line with key
}
fwrite($f,$line); //place $line back in file
}
这样,您将首先写入新数据,然后再写入原始数据.
This way you will write the new data first then the original data.
这篇关于尝试将文本插入文件到特定行上方的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!