将文件内容放入数组并更新保持订单的数据

I got a file called: test

In this file we got strings like:

  • apples
  • cars

I want to be able to edit the data: Cars while keeping the line breaks. If i edit array[1] it pushes them all together!.

So i want to change cars to like vans while keeping the file order in the end? I then get:

  • applesvans

My code:

$linesvol = file_get_contents('/srv/test');
$playlists = explode("
", $linesvol);
$playlists[1] = "vans
";
file_put_contents('/srv/test', implode($playlists));

You can use file() and preserve the line endings:

$playlists = file('/srv/test');
$playlists[1] = "vans
";
file_put_contents('/srv/test', implode($playlists));

Or implode on line endings:

$playlists = file('/srv/test', FILE_IGNORE_NEW_LINES);
$playlists[1] = "vans";
file_put_contents('/srv/test', implode("
", $playlists));

Note: If you are viewing this in some Windows applications you will not see newlines with , you need . Obviously, if you are viewing in a browser then you need nl2br().

You want to change the implode () to include line breaks.

Change from:

implode($playlists)

to:

implode("
", $playlists)