多余的空格和换行符 PHP 会自动删除 TEXTAREA [英] extra spaces and newline PHP automatically get removed TEXTAREA
问题描述
我输入php文件的代码如下.
<身体><form name="input" action="welcome.php" method="post">注释:<textarea name="input" rows="5" cols="40"></textarea><输入类型=提交"值=提交"></表单></html>
输出代码如下.
<身体>欢迎 <?php $a=$_POST["input"];回声 $a;?><br></html>
当输入任何带有额外空格和换行符的内容时,它会自动被删除.例如:
当我输入时:
abcdcda xyzb
输出为:
欢迎abcd cda xyzb
这是因为换行符表示为 \r\n
,在源代码中你会看到换行符.如果一个空格在 HTML 中紧跟另一个空格会被截断.
我建议你使用
标签,它不仅保存新行(就像 php 的nl2br()
) 但也保留了空格.在打印来自未知来源的输入时,不要忘记去除允许代码注入的字符.
使用
:
<身体><pre class="yourStyleForThisPreFormattedText">欢迎 <?php echo htmlentities($_POST["input"]);?>
</html>
使用特殊字符(
)和 PHP 函数:
<身体>欢迎 <?php $a = nl2br(str_replace(' ', ' ', 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 (
) and PHP functions:
<html>
<body>
Welcome <?php $a = nl2br(str_replace(' ', ' ', 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
这篇关于多余的空格和换行符 PHP 会自动删除 TEXTAREA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!