• shuffle()


    取数组若干个随机元素

    使用情景
    
    很多场合我们只是简单用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
    ?>
    比较详细的函数,可以试下:
    
    view sourceprint?
    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
    }
  • 相关阅读:
    数据结构-栈
    virtualenvwrapper 的安装和使用
    MySQL命令行本地登陆,远程登陆MySQL 的快捷键
    关于mysql8授权的问题,mysql萌新小白采坑记录
    史上最直接小白式的Sourcetree的分支创建与合并
    验证两个集合是否相等的方法
    VS开发工具的常用插件
    C# 数据库并发的解决方案(通用版、EF版)
    Jquery实现div左右重复来回走动
    描述符的应用
  • 原文地址:https://www.cnblogs.com/fyy-888/p/5381980.html
Copyright © 2020-2023  润新知