PHP regex question..adding commas
I have a list of va开发者_如何学运维lues 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,
thanks
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);
str_replace ( "\n", ",\n", $your_variable );
str_replace
would be enought for your needs
精彩评论