Skip to content
Advertisement

New line to paragraph function

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 text.

function nl2p($string, $line_breaks = true, $xml = true) {

$string = str_replace(array('<p>', '</p>', '<br>', '<br />'), '', $string);

// It is conceivable that people might still want single line-breaks
// without breaking into a new paragraph.
if ($line_breaks == true)
    return '<p>'.preg_replace(array("/([n]{2,})/i", "/([^>])n([^<])/i"), array("</p>n<p>", '<br'.($xml == true ? ' /' : '').'>'), trim($string)).'</p>';
else 
    return '<p>'.preg_replace(
    array("/([n]{2,})/i", "/([rn]{3,})/i","/([^>])n([^<])/i"),
    array("</p>n<p>", "</p>n<p>", '<br'.($xml == true ? ' /' : '').'>'),

    trim($string)).'</p>'; 

}

The problem is that whenever I try to create a single line break, it inadvertently removes the first character of the paragraph below it. I’m not familiar enough with regex to understand what is causing the problem.

Advertisement

Answer

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 <br>, 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('<p>', '</p>', '<br>', '<br />'), '', $string);

// It is conceivable that people might still want single line-breaks
// without breaking into a new paragraph.
if ($line_breaks == true)
    return '<p>'.preg_replace(array("/([n]{2,})/i", "/([^>])n([^<])/i"), array("</p>n<p>", '$1<br'.($xml == true ? ' /' : '').'>$2'), trim($string)).'</p>';
else 
    return '<p>'.preg_replace(
    array("/([n]{2,})/i", "/([rn]{3,})/i","/([^>])n([^<])/i"),
    array("</p>n<p>", "</p>n<p>", '$1<br'.($xml == true ? ' /' : '').'>$2'),

    trim($string)).'</p>'; 
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement