Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP multiple new lines

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
like image 239
DRKM Avatar asked Oct 29 '10 14:10

DRKM


3 Answers

Try this one:

$str = "Hello\n\n\n\n\nWorld\n\n\nHow\nAre\n\nYou?";
$str = preg_replace("/\n+/", "\n", $str);
print($str);
like image 172
kovshenin Avatar answered Oct 16 '22 07:10

kovshenin


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.

like image 25
Danny Staple Avatar answered Oct 16 '22 07:10

Danny Staple


$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.

like image 35
Marc B Avatar answered Oct 16 '22 06:10

Marc B