Alex Rivera | Logout

Replace multiple newlines, tabs, and spaces

Asked 2011-06-15T15:50:03.170
44

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.

Edit
Report

1 Answer

41

Use \R (which represents any line ending sequence):

$str = preg_replace('#\R+#', '</p><p>', $str);

It was found here: Replacing two new lines with paragraph tags

PHP documentation about Escape sequences:

\R (line break: matches \n, \r and \r\n)

answered 2013-04-29T09:00:11.827

Your Answer