Reputation: 1
I have a list of values like this in a .txt file:
aaa
bbbb
ddd
eeeee
How would I append a comma and a space to the end of all of them so that the list looks like this
aaa,
bbbb,
ddd,
eeeee,
Upvotes: 0
Views: 66
Reputation: 25554
str_replace ( "\n", ",\n", $your_variable );
str_replace
would be enought for your needs
Upvotes: 3
Reputation: 723388
No need for regex. Just get all the text from your file, do a good ol' str_replace()
and put it back in:
$contents = file_get_contents("myfile.txt");
$contents = str_replace("\n", ",\n", $contents);
file_put_contents("myfile.txt", $contents);
This doesn't insert a comma if the last line does not have a newline, but if you really need it to be there, here's an improved version that deals with that:
$contents = trim(file_get_contents("myfile.txt"));
$contents = str_replace("\n", ",\n", $contents) . ",";
file_put_contents("myfile.txt", $contents);
Upvotes: 5