I'm a little stuck. How to delete multiple lines of a new line with one new line. Between themselves there can be anything up to 20 new lines. for example
James said hi \ n \ n \ n \ n Test \ n Test two \ n \ n
The result is:
James said hi \ n Test \ n Test two \ n
Try the following:
$str = "Hello\n\n\n\n\nWorld\n\n\nHow\nAre\n\nYou?"; $str = preg_replace("/\n+/", "\n", $str); print($str);
Improving Marc B answer:
$fixed_text = preg_replace("\n(\s*\n)+", "\n", $text_to_fix);
Which should match the start new line, then at least one of the group of any number of spaces followed by a new line, and replace it with one new line.
$fixed_text = preg_replace("\n+", "\n", $text_to_fix);
This should do this, assuming that the consecutive lines of the new line are really consecutive and do not have spaces (tabs, spaces, carriage returns, etc.) between them.
$str = 'James said hello\n\n\n\n Test\n Test two\n\n'; echo preg_replace('{(\\\n)\1+}','$1',$str);