代码之家  ›  专栏  ›  技术社区  ›  Nrc

检测表单中的段落

php
  •  4
  • Nrc  · 技术社区  · 12 年前

    如何检测表单中有不同的段落?在本例中,如果用户编写不同的段落,则echo会将所有段落放在一起。我试过留白:pre,但没用。我不知道我还能做些什么来呼应文本 <p> ?

    CSS格式:

    #text {  
        white-space:pre;
    }
    

    HTML格式:

    <form action='normal-html.php' method='post'> 
    <textarea id="text" name='text' rows='15' cols='60'></textarea> <br/> 
    <input type='submit' value='Convertir a html' /> 
    </form> 
    
    <br />
    
    <?php
    $text = $_POST[text];
    echo $text;
    ?>
    
    2 回复  |  直到 12 年前
        1
  •  5
  •   Fluffeh    12 年前

    这听起来像是一份工作 http://php.net/manual/en/function.nl2br.php

    string nl2br ( string $string [, bool $is_xhtml = true ] )
    
    Returns string with '<br />' or '<br>' inserted before all 
    newlines (\r\n, \n\r, \n and \r). 
    

    您可以在回显数据时使用它,这样就永远不会更改数据库中的内容,也可以在将用户输入保存到数据库时简单地更改用户输入。就我个人而言,我是第一种选择的粉丝,但无论哪种都最适合你的应用程序。

    编辑:如果只想使用 <p> 标记,也可以使用 str_replace :

    $text = '<p>';
    $text.= str_replace('\n', '</p><p>', $_POST[text]);
    

    这个 \n 通常是一个新行,根据它的阅读方式,您可能需要使用 \r\n 而字符串替换将完成其余操作。这将留下一个备用 <p> 在绳子的末端,但你可以看到它的走向。

        2
  •  1
  •   fditz    12 年前

    您可以使用 爆炸 函数( php manual page ):

    $your_array = explode("\n", $your_string_from_db);
    

    例子:

    $str = "Lorem Ipsum\nAlle jacta est2\nblblbalbalbal";
    $arr = explode("\n", $str);
    
    foreach ( $arr as $item){
       echo "<p>".$item."</p>";
    }
    

    输出:

     Lorem Ipsum
     Alle jacta est 
     blblbalbalbal
    
    推荐文章