PHP将Textarea中的新行转换为<br/>

时间:2016-12-08 21:44:00

标签: javascript php jquery html

我有一个data.txt文件,它使用PHP将textarea中的内容发布到HTML页面。

我希望文本区域将新行读取为<br>元素,这样当我创建新行时,它们就不会在同一行上。

示例:

Hello
Hello

等于

HelloHello

但我希望它等于

Hello
Hello

我已经尝试过实施n2lbr,但很难用我的系统实现,所以如果你打算建议请说明一下。

这是我的代码:

HTML:

  <form method="POST" action="process.php" onsubmit='return validate ()' > 
    <textarea cols='60' rows='8' id="input1" type="text" name="myInputName" style="background:white;border:2px solid #dfdfdf;color:black;height:50px;"></textarea> 

    <input type="submit" name="submitButton" value="Post" style="width:60px;height:55px;background:white;color:black;border:2px solid #dfdfdf;" class="cbutton" /> 
  </form> 

  <form method="POST" action="clear.php">
    <input type="submit" name="Clear" value="Erase" style="width:265px;height:30px;background:white;color:black;border:2px solid #dfdfdf;margin-top:2px;" class="cbutton"/>
  </form>
</div>
<p style="font-size:35px;text-align:center;font-family:Raleway;">To do List</p>
<div id="list2" style="">

<?php
  $myfilename = "data.txt";
  if (file_exists($myfilename)) {
    echo file_get_contents($myfilename);
    nl2br($myfilename);
  }
?>

PHP(PROCESS.PHP):

<?php 
  // We will put the data into a file in the current directory called "data.txt" 
  // But first of all, we need to check if the user actually pushed submit 

  if (isset($_POST['submitButton'])) { 

    // The user clicked submit 
    // Put the contents of the text into the file 
    file_put_contents('./data.txt', $_POST['myInputName'] . '</br>', FILE_APPEND);
    $str = $_POST["myInputName"] echo nl2br($str);

    // ./data.txt: the text file in which the data will be stored 
    // $_POST['myInputName']: What the user put in the form field named "myInputName" 
    // FILE_APPEND: This tells the function to append to the file and not to overwrite it. 
    header('Location: index.php');
  } 

提前致谢!

这有很多麻烦。

2 个答案:

答案 0 :(得分:0)

您没有回显nl2br()的结果,您只是回显文件的原始内容,然后调用nl2br()并忽略它返回的内容。它应该是:

echo nl2br(file_get_contents($myfilename));

答案 1 :(得分:0)

只需使用PHP的内置函数nl2br(),就可以这样做:

  <?php
      $stringFromTextArea = "The Quick brown Fox\nStumble upon\nA Bag of Worms\n";
      $stringWithBR       = nl2br($stringFromTextArea);
      echo $stringWithBR;

同样的功能仍然可以用于使用file_get_contents()过筛的内容,如下所示:

  <?php
      $stringFromFile     = file_get_contents($pathToFile);
      $stringWithBR       = nl2br($stringFromFile);
      echo $stringWithBR;
相关问题