New line to paragraph function

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

    Here's an approach that comes with a reverse method to replace paragraphs back to regular line breaks and vice versa.

    These are useful to use when building a form input. When saving a users input you may want to convert line breaks to paragraph tags, however when editing the text in a form, you may not want the user to see any html characters. Then we would replace the paragraphs back to line breaks.

    // This function will convert newlines to HTML paragraphs
    // without paying attention to HTML tags. Feed it a raw string and it will
    // simply return that string sectioned into HTML paragraphs
    function nl2p($str) {
        $arr=explode("\n",$str);
        $out='';
    
        for($i=0;$i0)
                $out.='

    '.trim($arr[$i]).'

    '; } return $out; } // Return paragraph tags back to line breaks function p2nl($str) { $str = preg_replace("/]*?>/", "", $str); $str = str_replace("

    ", "\r\n", $str); return $str; }

提交回复
热议问题