我有一个textarea
表单,当用户按下enter
时显示新行,但是作为$_POST
变量,它将enters
保存为空格。我如何改变这一点,以便当用户按下回车键时,它在文本区插入一个不间断的空格,而不是一个空格?
的例子:
document.onPresskeySpace(insertBrElementInTextarea);
对于那些不知道textarea是什么样子的人来说,这是我的表单:
<form method="POST" action="process-page.php">
<input autocomplete="off" style="height: 60px; width: 95%; margin-left: 2.5%; box-sizing: border-box" class="form-control" type="text" name="name" placeholder="name"><br>
<textarea autocomplete="off" required="" style="min-height: 50px; max-height: 275px; width: 95%; margin-left: 2.5%; box-sizing: border-box" class="form-control" name="msg"></textarea><br>
<button style="width: 95%; margin-left: 2.5%; box-sizing: border-box" type="submit" name="submit" class="btn btn-dark">Publish</button>
</form>
也许您想使用nl2br() ?
实际上,他们并没有保存" enter ";作为"空格",他们将其保存为"n"(新行)
——https://en.wikipedia.org/wiki/Newline In_programming_languages
对于一些人来说,这很令人困惑,因为这个字符在数据库软件或phpmyadmin中没有显示。
我有一个建议。
如果你想用php在你的网页上显示它,你可以把这个字符(n)改成<br/>
...
<php echo str_replace("n", "<br/>", $your_variable); ?>
...
说明一下
非换行空格不是您应该使用的术语是非换行空格(html entity:
)不插入换行符。它的作用正好相反:即它防止两个单词之间的换行…
例如,假设你想确保一个人的名字不会中途换行,尽管你会使用这样的命令:
firstname lastname
在这种情况下,全名总是在一行;如果它的任何部分需要分隔到新行,则整个将放在新行上。
// Given the string
Hello there, my name is James Mason
// If the line limit is 30 characters (i.e. part way through the name then it'll output as
Hello there, my name is
James Mason
// If the string were not to have a non-breaking space
Hello there, my name is James Mason
// The output would be
Hello there, my name is James
Mason
更多信息可以在这里找到:
Wikipedia: non -break Space
如何修复
假设您正在向表单中的标准文本区域输入文本:
<form method="post" action="">
<textarea name="inputText"></textarea>
<input type="submit" value="Send Text">
</form>
然后当你按回车键时(如@HaniefHan所述),输入的字符是n
,通常你不能看到和在HTML中不是输出。例如:
echo "this is a
sentence that spans
over multiple lines";
将在一行中输出如下:
这是一个跨越多行的句子
但是,如果执行以下操作,仍然可以看到原始文本(在单独的行上):
- 查看页面源代码
- 输出
<pre>
标签内的文本
然而,由于我们倾向于在html标签内输出文本数据(例如<div>...</div>
),它将显示在一行上;假设屏幕宽度大于文本长度。
如果你想在HTML中显示换行符,那么你需要用<br>
替换n
,或者,根据你的用例,用<p>
(或替代标签)包裹段落。
// Using the example form from earlier
echo str_replace("n", "<br>", $_POST["inputText"]);
完整的代码示例
echo "
<form method='post' action=''>
<textarea name='inputText'></textarea>
<input type='submit' value='Send Text'>
</form>
";
echo str_replace("n", "<br>", $_POST["inputText"]);
// OR
# echo nl2br($_POST["inputText"]);
输入文字:
This is text with
multiple lines
of
input text.
原始输出:This is text with<br>multiple lines<br>of<br>input text.
显示为:
这是具有
多行
输入文本的文本。