php 捕获文本区域中的换行符(换行、换行)字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/289159/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 22:15:40  来源:igfitidea点击:

Capturing linebreaks (newline,linefeed) characters in a textarea

phphtmltextarealine-breaks

提问by lock

I have a form with a <textarea>and I want to capture any line breaks in that textarea on the server-side, and replace them with a <br/>.

我有一个带有 a 的表单,<textarea>我想捕获服务器端该 textarea 中的任何换行符,并将它们替换为<br/>.

Is that possible?

那可能吗?

I tried setting white-space:preon the textarea's CSS, but it's still not enough.

我尝试white-space:pretextarea的 CSS上进行设置,但仍然不够。

回答by Marc

Have a look at the nl2br()function. It should do exactly what you want.

看看nl2br()功能。它应该完全符合您的要求。

回答by Law

The nl2br()function exists to do exactly this:

nl2br()函数的存在正是为了做到这一点:

However, this function adds br tags but does not actually remove the new lines - this usually isn't an issue, but if you want to completely strip them and catch carriage returns as well, you should use a str_replaceor preg_replace

然而,这个函数添加了 br 标签,但实际上并没有删除新行——这通常不是问题,但如果你想完全去除它们并捕获回车,你应该使用 a str_replaceorpreg_replace

I think str_replace would be slightly faster but I have not benchmarked;

我认为 str_replace 会稍微快一点,但我没有进行基准测试;

$val = str_replace( array("\n","\r","\r\n"), '<br />', $val );

or

或者

$val = preg_replace( "#\n|\r|\r\n#", '<br />', $val );

回答by Law

If you're going to use str_replaceor preg_replace, you should probably place the "\r\n"at the beginning of the array, otherwise a \r\nsequence will be translated into two <br/>tags (since the \rwill be matched, and then the \nwill be matched).

如果您要使用str_replaceor preg_replace,您可能应该将 放在"\r\n"数组的开头,否则一个\r\n序列将被翻译成两个<br/>标签(因为\r将匹配,然后\n将匹配)。

eg:

例如:

$val = str_replace( array("\r\n", "\n","\r"), '<br />', $val );

or

或者

$val = preg_replace( "#\r\n|\n|\r#", '<br />', $val );

回答by cssyphus

For those wanting an answer that does not rely on nl2br():

对于那些想要不依赖于的答案的人nl2br()

$newList = ereg_replace( "\n",'|', $_POST['theTextareaContents']);

or (in this case):

或(在这种情况下):

$newList = ereg_replace( "\n",'<br/>', $_POST['theTextareaContents']);


PHP Side: from Textarea string to PHP string

PHP 端:从 Textarea 字符串到 PHP 字符串

$newList = ereg_replace( "\n",'|', $_POST['theTextareaContents']);

PHP Side: PHP string back to TextArea string:

PHP 端:PHP 字符串回 TextArea 字符串:

$list = str_replace('|', '&#13;&#10;', $r['db_field_name']);