Replace multiple newlines, tabs, and spaces
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)
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);
This is the answer, as I understand the question:
// Normalize newlines
preg_replace('/(\r\n|\r|\n)+/', "\n", $text);
// Replace whitespace characters with a single space
preg_replace('/\s+/', ' ', $text);
This is the actual function that I use to convert new lines to HTML line break and paragraph elements:
/**
*
* @param string $string
* @return string
*/
function nl2html($text)
{
return '<p>' . preg_replace(array('/(\r\n\r\n|\r\r|\n\n)(\s+)?/', '/\r\n|\r|\n/'),
array('</p><p>', '<br/>'), $text) . '</p>';
}