Reputation: 13
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;
}
}
Upvotes: 0
Views: 712
Reputation: 27864
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);
Upvotes: 0
Reputation: 324650
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")));
Upvotes: 2