des aed
des aed

Reputation: 1

Add a comma to the end of every line in a .txt file

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

Answers (2)

bensiu
bensiu

Reputation: 25554

str_replace ( "\n", ",\n", $your_variable );

str_replace would be enought for your needs

Upvotes: 3

BoltClock
BoltClock

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

Related Questions