php preg_replace在多行上复制字符串

I have the following file example:

apple,
cherry,
,(remove)
pear,
, (remove)
grapes,
watermelon

I've used the following expression

preg_replace('/,+/', ',', $n);

from this answer.

This works fine but only if the file is on one line:

apple, cherry,, pear,,...

How do I extend the expression to remove excess duplicates on multiple lines so the file reads:

apple,
cherry,
pear,
grapes,
watermelon

Here is the code:

foreach ($lines as $line_num => $line) {
if ($line[0] === '.') { $compare_line = $line; $compare_line = preg_replace('/,+/', ',', $compare_line); echo $compare_line; } }

My guess is that you are doing something to split the lines and then only applying the regex to the first line. Try just doing this:

file_put_contents("newfile.txt",preg_replace("/,+/", ",", file_get_contents("oldfile.txt")));

You can make preg_replace handle all the lines as one single line by adding the flag /s to the end of the expression.

preg_replace('/,+/s', ',', $n);