如何在 html textarea POST 数据中保留换行符

How to keep linebreaks in html textarea POST data

我正在尝试将歌曲的歌词提交到文本区域。所以,这需要在我输出时保留换行符。我知道浏览器标准应该使用 \r\n 作为换行符,而 PHP 的 nl2br() 函数可以将 \r\n 转换为 <br> 标签。

我也知道 textarea 输入需要 wrap="hard" 才能传递换行符,否则 wrap="soft" 的默认值将被忽略,并且 cols=使用 wrap="hard" 时必须指定 ""。我试图用下面的 html 来完成这个:

<textarea wrap="hard" name="reading_text" cols="450" rows="6" maxlength="5000"></textarea>

但是,POST 数组不显示任何换行符。我将其输入文本区域:

Line one of the lyrics

That were entered into the textarea

Alas to my dismay

Red eyes and fire and signs

Because the line-breaks are not in the POST data

I want to make a ray of sunshine and never leave home

我在 POST 数组中得到这个:

array(5) { ["reading_text"]=> string(216) "Line one of the lyrics That were entered into the textarea Alas to my dismay Red eyes and fire and signs Because the line-breaks are not in the POST data" ["add_reading"]=> string(3) "Add" }

为了让事情变得更加混乱,我尝试查看 W3 Schools 演示 (https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_textarea_wrap)。但是,我似乎甚至无法使该示例起作用。当我在文本区域中输入许多换行符时,文本出来时没有 \r\n.

我在这里错过了什么?

可以将文本区域文本作为查询字符串的一部分传递。这将强制整个字符串 url 编码如下:

%0AGray%2C%20quiet%20and%20tired%20and%20mean%0A%0APicking%20at%20a%20worried%20seam%0A%0AI%20try%20to%20make%20you%20mad%20at%20me%20over%20the%20phone.%0A%0ARed%20eyes%20and%20fire%20and%20signs%0A%0AI%27m%20taken%20by%20a%20nursery%20rhyme%0A%0AI%20want%20to%20make%20a%20ray%20of%20sunshine%20and%20never%20leave%20home%0A

然后用urldecode()解码接收页面上的字符串。这应该保持格式并正确显示。

http://php.net/manual/en/function.urldecode.php

https://www.tools4noobs.com/online_php_functions/urldecode/

我想您也可以在 POSTING 之前 urlencode() textarea 文本,然后在另一端 urldecode 。

关于 wrap 属性,您不需要它来实现您想要实现的目标。如 HTML 5.2 specification 中所述,当使用 softhard 属性选项时,文本中的换行符将被保留。

仅当您想限制每行输入的长度时才需要hard选项。使用此选项可在您的输入自然换行的任何地方强制使用额外的换行符(即,无论该行长于 cols 中设置的值)。

例如,如果我有一个设置为 cols="20" wrap="hard" 的文本区域并且我输入文本:

This is a long string that will exceed the number of cols in this textarea

那么提交的值会变成:

This is a long
string that will
exceed the number of
cols in this
textarea

如果我没理解错的话,你只想保留用户有意输入的换行符;这些将使用默认 soft 选项捕获。

关于提交的文本,请注意,转义字符\r\n不会出现在发布的值中,换行符仍然是相同的解释形式就像您按下键盘上的 "enter" 键时一样。

即使您看不到转义字符,但换行符确实存在并且仍然可以被 PHP 找到和操作。正如您所建议的,nl2br 可用于将新行转换为 HTML 中断元素。

如果您确实需要将换行符转换为相应的转义字符,也许是在存储值之前,那么可以通过多种方式来操作字符串。几个例子:

$escaped_newlines = str_replace("\r\n", '\r\n', $_POST['reading_text']);
$escaped_newlines = preg_replace('/\r\n/', '\r\n', $_POST['reading_text']);

(为了进一步阅读,有一个有用的 S.O。关于 double/single quotes and interpreting newlines 的回答)

最后,您目前如何查看 $_POST 的内容?如果将 var_dump 的内容直接输出到 HTML,则需要将输出包装在 <pre></pre> 标记中,以便在结果 [=57] 中看到换行符=].更好的是,输出到日志文件,这样您就不需要考虑此类渲染问题。

这是最终解决问题的方法:在输出或存储到要删除的数据库之前,我在字符串上使用了 PHP 的过滤器 FILTER_FLAG_STRIP_LOW (http://php.net/manual/en/filter.filters.flags.php)换行符 \r\n .

要解决此问题,您可以使用 FILTER_FLAG_ENCODE_LOW 而不是 FILTER_FLAG_STRIP_LOW

$input = filter_var($input, FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);