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


       使用情景

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

    先来看看nl2br() 函数吧。

    定义和用法

    nl2br() 函数在字符串中的每个新行 ( ) 之前插入 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(" ""</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("/([ ]{2,})/i","/([^>]) ([^<])/i"), array("</p> <p>"'<br'.($xml == true ? ' /' :'').'>'), trim($string)).'</p>';
    18     else
    19         return '<p>'.preg_replace("/([ ]{1,})/i""</p> <p>", trim($string)).'</p>';
    20 }
  • 相关阅读:
    小程序 wx.navigateTo和 wx.redirectTo区别
    小程序返回上一级页面背景音乐报错 setBackgroundAudioState:fail title is nil!;
    centos7 安装RabbitMQ3.6.15 以及各种报错
    MYSQL创建分区时候报错
    scrapy操作mysql/批量下载图片
    深入浅出TCP与IP协议笔记
    python反射详解
    python迭代器
    python生成器
    loggong模块
  • 原文地址:https://www.cnblogs.com/hejianrong/p/5802010.html
Copyright © 2020-2023  润新知