extra spaces and newline PHP automatically get removed TEXTAREA

三世轮回 提交于 2019-12-24 14:24:57

问题


My code for the input php file is the following.

<!DOCTYPE html>
<html>
  <body>
    <form name="input" action="welcome.php" method="post">
      Comment: <textarea name="input" rows="5" cols="40"></textarea>
      <input type="submit" value="Submit">
    </form> 
  </body>
</html>

For the output code it is the following.

<html>
  <body>
    Welcome <?php $a=$_POST["input"]; echo $a; ?><br>
  </body>
</html>

When anything with extra spaces and newline are inputted, it automatically gets removed. For example :

When I input:

abcd
cda xyzb

Output is:

Welcome abcd cda xyzb


回答1:


This is because new line characters are represented as \r\n, in the sourcecode you'll see new lines. Whitespaces get truncated if one follows another in HTML.

I suggest you to use the <pre> tag, which does not only save the new lines (like php's nl2br()) but also preserves the whitespaces.

Don't forget to strip characters that would allow code injection when printing input from unknown source.

Using <pre>:

<html>
<body>
<pre class="yourStyleForThisPreFormattedText">
Welcome <?php echo htmlentities($_POST["input"]); ?>
</pre>
</body>
</html>

Using special chars (&nbsp;) and PHP functions:

<html>
<body>
Welcome <?php $a = nl2br(str_replace(' ', '&nbsp;', htmlentities($_POST["input"])), true); 
echo $a; ?>
</body>
</html>

Notice:

For HTML4 and HTML5 use nl2br($str, true);, for XHTML4 use nl2br($str); - the difference is in the output: <br> and <br />. See http://php.net/nl2br




回答2:


To display newline use nl2br()

<html>
    <body>
        Welcome <?php $a = nl2br($_POST["input"]); 
        echo $a; ?><br>
    </body>
</html>

You can also add <pre> tag to show preformatted text (all whitespaces).




回答3:


Change

<textarea name="input" rows="5" cols="40"></textarea>

Into

<textarea name="input" rows="5" cols="40" wrap="virtual"></textarea>

You can also use wrap: off, hard, soft, physical




回答4:


Try this...

Welcome <?php echo htmlentities($_POST['input']); ?>

htmlentities() converts your HTML.



来源:https://stackoverflow.com/questions/19313307/extra-spaces-and-newline-php-automatically-get-removed-textarea

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!