Keep Line Breaks from Textarea [duplicate]

2019-06-21 11:03发布

This question already has an answer here:

I am getting input from a user in a form via PHP in a WordPress site (an address specifically) and I want to be able to display the information that I gather with the same line breaks (separating out the different components of the address) on a different page. It displays correctly if I put it into a textarea, but if I get the data and echo it into a div by itself, it doesn't maintain the line breaks. What can I do?

5条回答
成全新的幸福
2楼-- · 2019-06-21 11:41

Use <pre> tag for example. But it will look quite ugly.

Or replace line breaks with <br/>

查看更多
该账号已被封号
3楼-- · 2019-06-21 11:44

HTML collapses any amount of whitespace (except non breaking space) including new lines to a single space. In order to maintain new lines, you will need to replace new lines with <br> or use <pre> tags or use one of the white-space CSS rules designed to control this behaviour.

查看更多
贼婆χ
4楼-- · 2019-06-21 11:51

You can use echo nl2br( $string) to convert \n to <br> HTML line break.

查看更多
该账号已被封号
5楼-- · 2019-06-21 12:02

you want to utilize the white-space css attribute http://www.w3schools.com/cssref/pr_text_white-space.asp

So you'll have something like

<p class="whitespace"><?= $input_from_textarea ?></p>

with css:

.whitespace { 
    white-space: pre-wrap; 
}

Do not manually clean your input replacing new line elements with break tags. It makes your data less reusable and is a lot more work.

You can use the php function nl2br() but it does not give you as much control as manipulating the display through css.

查看更多
倾城 Initia
6楼-- · 2019-06-21 12:03

use nl2br() method to ratain your . nl2br($text); for more quires check this http://www.php.net/manual/en/function.nl2br.php

查看更多
登录 后发表回答