PHP fwrite()如何在某些特定行之后插入新行

我是新来的.
无论如何,我对fwrite()进行了研究,但是我找不到解决方案,所以我正在寻求帮助.
我想要的是f.e.在其他特定行之后添加新的文本行.
F.E.我有一个.txt文件,其中有:

//Users

//Other stuff

//Other stuff2  

现在我想做的是能够在//用户下面添加一个新用户而不用触及“其他东西”和“其他东西2”.所以看起来应该是这样的:

//Users    
Aneszej  
Test321  
Test123

//Other stuff

//Other stuff2  

到目前为止我所拥有的:

$config = 'test.txt';
$file=fopen($config,"r+") or exit("Unable to open file!");

$date = date("F j, Y");
$time = date("H:i:s");

$username = "user";
$password = "pass";
$email = "email";
$newuser = $username . " " . $password . " " . $email . " " . $date . " " . $time;

while (!feof($file)) {
    $line=fgets($file);
    if (strpos($line, '//Users')!==false) {
        $newline = PHP_EOL . $newuser;
    }

}

fwrite($file, $newline);

fclose($file);

test.txt文件

//Users

//Something Else

//Something Else 2

但这只会将用户写入.txt文件的末尾.

非常感谢大家的帮助!它已经解决了.

解决方法:

我修改了你的代码,我认为以下是你需要的,我也放了评论,下面的功能会不断添加新用户,你可以添加检查用户存在的条件.

$config = 'test.txt';
$file=fopen($config,"r+") or exit("Unable to open file!");

$date = date("F j, Y");
$time = date("H:i:s");

$username = "user";
$password = "pass";
$email = "email";
$newuser = $username . " " . $password . " " . $email . " " . $date . " " .    $time."\r\n";   // I added new line after new user
$insertPos=0;  // variable for saving //Users position
while (!feof($file)) {
    $line=fgets($file);
    if (strpos($line, '//Users')!==false) { 
        $insertPos=ftell($file);    // ftell will tell the position where the pointer moved, here is the new line after //Users.
        $newline =  $newuser;
    } else {
        $newline.=$line;   // append existing data with new data of user
    }
}

fseek($file,$insertPos);   // move pointer to the file position where we saved above 
fwrite($file, $newline);

fclose($file);
上一篇:使用PHP通过字符串中搜索查询的位置对MySQL的搜索结果进行排序


下一篇:PHP判断客户端为PC还是手机