我正在尝试将歌曲的歌词提交到文本区域。所以,这需要在我输出时保留换行符。我知道浏览器标准应该使用 \r\n
作为换行符,PHP 的 nl2br() 函数可以转换 \r\n
进入<br>
标签。
我也知道 textarea 输入需要 wrap="hard"才能传递换行符,否则 wrap="soft"的默认值将被忽略,并且必须指定 cols=""使用换行=“硬”。我试图用下面的 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
.
我在这里错过了什么?
最佳答案
关于 wrap
属性,您不需要它来实现您想要实现的目标。如 HTML 5.2 specification 中所述, 当使用 either soft
时,文本中的换行符被保留或 hard
属性选项。
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
不会在发布的值中看到,换行符仍采用与您按下键盘上的“输入”键时相同的解释形式。
即使您看不到转义字符,换行符也确实存在并且仍然可以被 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']);
(为了进一步阅读,关于 double/single quotes and interpreting newlines 有一个有用的 S.O. 答案)
最后,您目前如何查看 $_POST
的内容? ?如果您要输出 var_dump
的内容直接进入 HTML,那么您需要将输出包装在 <pre></pre>
中标记以便在生成的 HTML 中查看换行符。更好的是,输出到日志文件,这样您就不需要考虑此类渲染问题。
关于php - 如何在 html textarea POST 数据中保留换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54994084/