开发者

Capture newline from a textarea input

开发者 https://www.devze.com 2023-03-01 14:55 出处:网络
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.

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.

Currently if the user e开发者_高级运维nters:

Apple
Google
MS

and my PHP code is:

$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?


Try nl2br() instead:

echo nl2br($str);


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).


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

To convert \n to <br> use:

echo nl2br( $str );
0

精彩评论

暂无评论...
验证码 换一张
取 消