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

时间:2024-01-20 13:23:33

  使用情景

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

先来看看nl2br() 函数吧。

定义和用法

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

一个简单的例子:

1 <?php
2  
3 $str = "Welcome to
4 www.nowamagic.net";
5  
6 echo nl2br($str);
7  
8 ?>

运行结果的HTML代码:

1 Welcome to <br />
2 www.nowamagic.net

nl2p

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

1 <?php
2 function nl2p($text) {
3   return "<p>" str_replace("\n""</p><p>"$text) . "</p>";
4 }
5 ?>

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

01 /**
02  * Returns string with newline formatting converted into HTML paragraphs.
03  *
04  * @param string $string String to be formatted.
05  * @param boolean $line_breaks When true, single-line line-breaks will be converted to HTML break tags.
06  * @param boolean $xml When true, an XML self-closing tag will be applied to break tags (<br />).
07  * @return string
08  */
09 function nl2p($string$line_breaks = true, $xml = true)
10 {
11     // Remove existing HTML formatting to avoid double-wrapping things
12     $string str_replace(array('<p>''</p>''<br>''<br />'), '',$string);
13      
14     // It is conceivable that people might still want single line-breaks
15     // without breaking into a new paragraph.
16     if ($line_breaks == true)
17         return '<p>'.preg_replace(array("/([\n]{2,})/i","/([^>])\n([^<])/i"), array("</p>\n<p>"'<br'.($xml == true ? ' /' :'').'>'), trim($string)).'</p>';
18     else
19         return '<p>'.preg_replace("/([\n]{1,})/i""</p>\n<p>", trim($string)).'</p>';
20 }