簡體   English   中英

PHP將Textarea中的新行轉換為<BR>

[英]PHP Convert New Line in Textarea to <BR>

我有一個data.txt文件,該文件將其中的內容從文本區域發布到PHP的HTML頁面。

我希望文本區域將新行作為<br>元素讀取<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');
  } 

提前致謝!

對此有很多麻煩。

您不是在回顯nl2br()的結果, nl2br()在回顯文件的原始內容,然后調用nl2br()並忽略其返回的內容。 它應該是:

echo nl2br(file_get_contents($myfilename));

只需使用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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM