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\",
Replace the head and the end of string or document!
preg_replace('/(^[^a-zA-Z]+)|([^a-zA-Z]+$)/','',$match);
You need the multiline modifier to match multiple lines:
preg_replace("/PATTERN/m", "REPLACE", $text);
Also in your example you seem to be replacing 2+ newlines with exactly 2, which isn't what your question indicates.
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>';
}
I would suggest something like this:
preg_replace("/(\R){2,}/", "$1", $str);
This will take care of all the Unicode newline characters.