Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm new here.
Anyway, I did my research on fwrite(), but I couldn't find solution, so i'm asking for help. What I want is f.e. to add a new line of text after some other specific line. F.e. I have a .txt file in which there is:

//Users

//Other stuff

//Other stuff2  

Now what I'd like to do is be able to add a new user below //Users without touching "Other Stuff" and "Other Stuff 2". So it should look something like this:

//Users    
Aneszej  
Test321  
Test123

//Other stuff

//Other stuff2  

What I have so far:

$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 file

//Users

//Something Else

//Something Else 2

But this only writes users to the end of the .txt file.

Thanks a lot everyone for your help! It's solved.

like image 276
Aneszej Avatar asked May 16 '13 21:05

Aneszej


1 Answers

I modified your code, I think follows is what you need, and I also put comment, function below will keep adding new user, you can add condition that to check user exist.

$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);
like image 147
Ming M Zheng Avatar answered Nov 11 '22 07:11

Ming M Zheng