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

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...