Home  >  Article  >  Backend Development  >  PHP文本换行转
函数nl2br()与nl2p()文本换行转p段落

PHP文本换行转
函数nl2br()与nl2p()文本换行转p段落

WBOY
WBOYOriginal
2016-06-20 13:01:452060browse

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

先来看看nl2br() 函数吧。

定义和用法

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

一个简单的例子:

<?php $str = "Welcome to 
www.scutephp.com";
        
echo nl2br($str);
        
?>

运行结果的HTML代码:

Welcome to <br>
www.scutephp.com

nl2p

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

<?php function nl2p($text) {
  return "<p>" . str_replace("\n", "<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([^\n</p><p>", '<br true :>'), trim($string)).'</p>';
    else
        return '<p>'.preg_replace("/([\n]{1,})/i", "</p>\n<p>", trim($string)).'</p>';
}


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn