php 从 textarea 输入捕获换行符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5844465/
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-25 22:39:13  来源:igfitidea点击:

Capture newline from a textarea input

phphtml

提问by Pritesh Desai

I have a textarea form in my html. If the user hits enter between 2 sentences that data should be carried over to my PHP.

我的 html 中有一个 textarea 表单。如果用户在 2 个句子之间点击输入,则数据应转移到我的 PHP 中。

Currently if the user enters:

当前,如果用户输入:

Apple
Google
MS

and my PHP code is:

我的 PHP 代码是:

$str = $_POST["field"];

echo $str;

I get

我得到

Apple Google MS 

as the output. I want output to be like this

作为输出。我希望输出是这样的

Apple
Google
MS

what should I do?

我该怎么办?

回答by Alix Axel

Try nl2br()instead:

试试吧nl2br()

echo nl2br($str);

回答by Thilo

The newlines should be included in the string that you get from $_POST["field"]. However, if you then use that string as output in HTML, newlines will be treated as whitespace. To force the line breaks, use preg_replace("/\n/", "<br />", $str).

换行符应包含在您从$_POST["field"]. 但是,如果您随后将该字符串用作 HTML 中的输出,则换行符将被视为空格。要强制换行,请使用preg_replace("/\n/", "<br />", $str)

回答by Galen

This is because when you echo it it's being displayed as HTML. A \ncharacter is interpreted as a space. If you view the source you'll see your desired output.

这是因为当您回显它时,它会显示为 HTML。一个\n字符被解释为一个空格。如果您查看源代码,您将看到所需的输出。

To convert \nto <br>use:

转换\n<br>使用:

echo nl2br( $str );