New line to paragraph function

前端 未结 7 1047
情话喂你
情话喂你 2021-01-31 09:20

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

7条回答
  •  再見小時候
    2021-01-31 09:39

    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)).'

    '; }

提交回复
热议问题