本文实例讲述了php函数nl2br()与自定义函数nl2p()换行用法。分享给大家供大家参考,具体如下:
使用情景
很多场合我们只是简单用textarea获取用户的长篇输入,而没有用编辑器。用户输入的换行以“n”的方式入库,输出的时候有时候会没有换行,一大片文字直接出来了。这个时候可以根据库里的“n”给文字换行。php有自带的函数nl2br(),我们也可以自定义函数nl2p()。
先来看看nl2br() 函数吧。
定义和用法
nl2br() 函数在字符串中的每个新行 (n) 之前插入 html 换行符 (<br />)。
一个简单的例子:
<?php $str = "welcome to www.jb51.net"; echo nl2br($str); ?>
运行结果的html代码:
welcome to <br /> www.jb51.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>';
}
更多关于php相关内容感兴趣的读者可查看本站专题:《php运算与运算符用法总结》、《php网络编程技巧总结》、《php基本语法入门教程》、《php操作office文档技巧总结(包括word,excel,access,ppt)》、《php日期与时间用法总结》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家php程序设计有所帮助。
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!