且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

多余的空格和换行符 PHP 会自动删除 TEXTAREA

更新时间:2022-12-28 16:27:54

这是因为换行符表示为 \r\n,在源代码中你会看到换行符.如果一个空格在 HTML 中紧跟另一个空格会被截断.

我建议你使用

 标签,它不仅保存新行(就像 php 的 nl2br()) 但也保留了空格.

在打印来自未知来源的输入时,不要忘记去除允许代码注入的字符.

使用
:

<身体><pre class="yourStyleForThisPreFormattedText">欢迎 <?php echo htmlentities($_POST["input"]);?>

</html>

使用特殊字符(&nbsp;)和 PHP 函数:

<身体>欢迎 <?php $a = nl2br(str_replace(' ', '&nbsp;', htmlentities($_POST["input"])), true);回声 $a;?></html>

注意:

对于 HTML4 和 HTML5 使用 nl2br($str, true);,对于 XHTML4 使用 nl2br($str); - 不同之处在于输出:

.请参阅 http://php.net/nl2br

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

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