How do I replace multiple consecutive newlines with one newline. There could be up to 20 newlines next to each other. For example
James said hello\n\n\n\n Test\n Test two\n\n
Should end up as:
James said hello\n Test\n Test two\n
Try this one:
$str = "Hello\n\n\n\n\nWorld\n\n\nHow\nAre\n\nYou?";
$str = preg_replace("/\n+/", "\n", $str);
print($str);
Improving on Marc B's answer:
$fixed_text = preg_replace("\n(\s*\n)+", "\n", $text_to_fix);
Which should match an initial newline, then at least one of a group of any amount of whitespace followed by a newline and replace it all with a single newline.
$fixed_text = preg_replace("\n+", "\n", $text_to_fix);
This should do it, assuming that the consecutive newlines are truly consecutive and don't have any whitespace (tabs, spaces, carriage returns, etc...) between them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With