为什么 CRLF 在使用 php 分配给 <input> 时转换为 LF

why CRLF transformed to LF when they are assigned to <input> using php

(1)一个表单包含文本区域,输入文本换行符为it.Like :

一个
b

然后提交表单并将文本存储到database.The 内容长度是4.I 可以输出它们的ascii 码,使用ord() function.They 是97 (a), 13(cr), 10(lf), 98(b).

(2)使用smarty.Like:

获取内容并赋值给模板
//$string is get from database.
$smarty->assign('str', $string);

使用输入元素将内容存储在 html 模板中。

<input id="test" type="hidden" value="{$str}">

(3)获取输入值的长度

document.getElementById("test").value.length;    //the result is 3

正在使用

{$str|@strlen}    //the result is 4

如果我提交表格并得到cotents的ascii码,它们是97(a), 10(lf) , 98(b)。字符 13(cr) 丢失。

我在谷歌上搜索了很多,但没有找到原因。有什么解释吗?非常感谢。


我找到了这个:

https://bugzilla.mozilla.org/show_bug.cgi?id=188015

评论28有人回复,官方文档转至:

http://www.w3.org/TR/html5/syntax.html#preprocessing-the-input-stream

"CR" (U+000D) characters and "LF" (U+000A) characters are treated specially. All CR characters must be converted to LF characters, and any LF characters that immediately follow a CR character must be ignored.

希望能有所帮助。

发生的事情是你的 html 得到了这样的渲染(我已经转义了 cr 字符:)

<input id="test" type="hidden" value="a
b">

并且浏览器会修剪空格,从而删除 CR 字符。

您可以做的是呈现 urlencode($str) 而不是普通的 $str 变量。这样浏览器就不会弄乱你的控制字符。不过,您必须在另一侧进行 urldecode。