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


PHP fwrite() how to insert a new line after some specific line

我是新来的。
无论如何,我做了我的研究fwrite(),但我找不到解决方案,所以我寻求帮助。我想要的是f.e.在一些其他特定的行之后添加一个新的文本行。例如,我有一个。txt文件,其中有:
//Users
//Other stuff
//Other stuff2  

现在我想做的是能够在//Users下面添加一个新用户,而不需要触摸"Other Stuff"answers"Other Stuff 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);

用法文件
//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-variable中并最终覆盖该文件,要么像Robert Rozas评论中提到的那样,使用fseek倒回光标。这应该在你读到"Something else"这一行的时候完成。

Try fseek:

<?php
 $file = fopen($filename, "c");
 fseek($file, -3, SEEK_END);
 fwrite($file, "whatever you want to write");
 fclose($file);
?>

PHP Doc: http://php.net/manual/en/function.fseek.php

您需要找到'//Users'后的break。一直读到文件的末尾