Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace multiple newlines, tabs, and spaces

I want to replace multiple newline characters with one newline character, and multiple spaces with a single space.

I tried preg_replace("/\n\n+/", "\n", $text); and failed!

I also do this job on the $text for formatting.

$text = wordwrap($text, 120, '<br/>', true); $text = nl2br($text); 

$text is a large text taken from user for BLOG, and for a better formatting I use wordwrap.

like image 288
Sourav Avatar asked Jun 15 '11 15:06

Sourav


1 Answers

In theory, you regular expression does work, but the problem is that not all operating system and browsers send only \n at the end of string. Many will also send a \r.

Try:

I've simplified this one:

preg_replace("/(\r?\n){2,}/", "\n\n", $text); 

And to address the problem of some sending \r only:

preg_replace("/[\r\n]{2,}/", "\n\n", $text); 

Based on your update:

// Replace multiple (one ore more) line breaks with a single one. $text = preg_replace("/[\r\n]+/", "\n", $text);  $text = wordwrap($text,120, '<br/>', true); $text = nl2br($text); 
like image 176
Francois Deschenes Avatar answered Sep 21 '22 23:09

Francois Deschenes