网络编程 
首页 > 网络编程 > 浏览文章

PHP函数nl2br()与自定义函数nl2p()换行用法分析

(编辑:jimmy 日期: 2024/5/20 浏览:3 次 )

本文实例讲述了PHP函数nl2br()与自定义函数nl2p()换行用法。分享给大家供大家参考,具体如下:

使用情景

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

先来看看nl2br() 函数吧。

定义和用法

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

一个简单的例子:

<"Welcome to 
www.jb51.net";
echo nl2br($str);
"htmlcode">
Welcome to <br />
www.jb51.net

nl2p

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

<"<p>" . str_replace("\n", "</p><p>", $text) . "</p>";
}
"htmlcode">
/**
 * 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 "/([\n]{1,})/i", "</p>\n<p>", trim($string)).'</p>';
}

更多关于PHP相关内容感兴趣的读者可查看本站专题:《PHP运算与运算符用法总结》、《PHP网络编程技巧总结》、《PHP基本语法入门教程》、《php操作office文档技巧总结(包括word,excel,access,ppt)》、《php日期与时间用法总结》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》

希望本文所述对大家PHP程序设计有所帮助。

上一篇:php通过curl添加cookie伪造登陆抓取数据的方法
下一篇:PHP使用stream_context_create()模拟POST/GET请求的方法