[英]PHP fwrite() how to insert a new line after some specific line
我是新來的。
無論如何,我對fwrite()進行了研究,但找不到解決方案,因此我尋求幫助。 我想要的是fe在其他一些特定行之后添加新行文本。 如果我有一個.txt文件,其中有:
//Users
//Other stuff
//Other stuff2
現在,我想做的是能夠在// Users下面添加一個新用戶,而無需觸摸“ Other Stuff”和“ 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);
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-variable中,然后最后覆蓋文件,要么按照Robert Rozas的評論中的fseek倒帶光標。 閱讀“其他內容”這一行后,應立即執行此操作。
嘗試fseek:
<?php
$file = fopen($filename, "c");
fseek($file, -3, SEEK_END);
fwrite($file, "whatever you want to write");
fclose($file);
?>
找到“ // Users”后,需要break
。 您一直在閱讀文件的末尾。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.