I have this interesting function that I\'m using to create new lines into paragraphs. I\'m using it instead of the nl2br()
function, as it outputs better formatted
The problem is with your match for single line breaks. It matches the last character before the line break and the first after. Then you replace the match with
, so you lose those characters as well. You need to keep them in the replacement.
Try this:
function nl2p($string, $line_breaks = true, $xml = true) {
$string = str_replace(array('', '
', '
', '
'), '', $string);
// It is conceivable that people might still want single line-breaks
// without breaking into a new paragraph.
if ($line_breaks == true)
return ''.preg_replace(array("/([\n]{2,})/i", "/([^>])\n([^<])/i"), array("
\n", '$1
$2'), trim($string)).'
';
else
return ''.preg_replace(
array("/([\n]{2,})/i", "/([\r\n]{3,})/i","/([^>])\n([^<])/i"),
array("
\n", "
\n", '$1
$2'),
trim($string)).'
';
}