New line to paragraph function

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

    Here is another approach that doesn't use regular expressions. Note, this function will remove any single line-breaks.

    function nl2p($string)
    {
        $paragraphs = '';
    
        foreach (explode("\n", $string) as $line) {
            if (trim($line)) {
                $paragraphs .= '

    ' . $line . '

    '; } } return $paragraphs; }

    If you only need to do this once in your app and don't want to create a function, it can easily be done inline:

    
        
            

提交回复
热议问题