New line to paragraph function

前端 未结 7 1114
情话喂你
情话喂你 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:45

    @Laurent's answer wasn't working for me - the else statement was doing what the $line_breaks == true statement should have been doing, and it was making multiple line breaks into
    tags, which PHP's native nl2br() already does.

    Here's what I managed to get working with the expected behavior:

    function nl2p( $string, $line_breaks = true, $xml = true ) {
    
        // Remove current tags to avoid double-wrapping.
        $string = str_replace( array( '

    ', '

    ', '
    ', '
    ' ), '', $string ); // Default: Use
    for single line breaks,

    for multiple line breaks. if ( $line_breaks == true ) { $string = '

    ' . preg_replace( array( "/([\n]{2,})/i", "/([\r\n]{3,})/i", "/([^>])\n([^<])/i" ), array( "

    \n

    ", "

    \n

    ", '$1$2' ), trim( $string ) ) . '

    '; // Use

    for all line breaks if $line_breaks is set to false. } else { $string = '

    ' . preg_replace( array( "/([\n]{1,})/i", "/([\r]{1,})/i" ), "

    \n

    ", trim( $string ) ) . '

    '; } // Remove empty paragraph tags. $string = str_replace( '

    ', '', $string ); // Return string. return $string; }

提交回复
热议问题