nl2br()与nl2p()函数,php在字符串中的新行(\n)之前插入换行符

   使用情景

很多场合我们只是简单用textarea获取用户的长篇输入,而没有用编辑器。用户输入的换行以“\n”的方式入库,输出的时候有时候会没有换行,一大片文字直接出来了。这个时候可以根据库里的“\n”给文字换行。PHP有自带的函数nl2br(),我们也可以自定义函数nl2p()。

先来看看nl2br() 函数吧。

定义和用法

nl2br() 函数在字符串中的每个新行 (\n) 之前插入 HTML 换行符 (<br />)。

一个简单的例子:

     <?php
    $str = "Welcome to
    www.nowamagic.net";
    echo nl2br($str);
    ?>
运行结果的HTML代码:
    Welcome to <br />
    www.nowamagic.net

nl2p
nl2br 有个缺点,比如要用CSS做到段落缩进就比较麻烦,这个时候就需要 nl2p 了。将br换行换成段落p换行,比较简单是直接替换:

<?php function nl2p($text) { return "<p>" . str_replace("\n", "</p><p>", $text) . "</p>"; } ?>

比较详细的函数,可以试下:

/**
     * Returns string with newline formatting converted into HTML paragraphs.
     *
     * @param string $string String to be formatted.
     * @param boolean $line_breaks When true, single-line line-breaks will be converted to HTML break tags.
     * @param boolean $xml When true, an XML self-closing tag will be applied to break tags (<br />).
     * @return string
     */
    function nl2p($string, $line_breaks = true, $xml = true)
    {
        // Remove existing HTML formatting to avoid double-wrapping things
        $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("/([\n]{1,})/i", "</p>\n<p>", trim($string)).'</p>';
    }

https://www.cnblogs.com/hejianrong/p/5802010.html

原文地址:https://www.cnblogs.com/lxwphp/p/15454619.html