保留文本区域中的换行符

我有一个带有文本区域的表单,我希望在输出内容时保留用户输入的换行符。

例如,如果我用 textarea 写:

这是一个句子。这是另一个。这是另一个。

这是一个新段落。这是一个新句子。这是另一个。

我想要相同的输出和 没有:

这是一个句子。这是另一个句子。这是另一个句子。这是一个新句子 这是一个新的句子。这是另一个。

如何保留换行符?

108306 次浏览

The line breaks the user entered are preserved, neither html nor php simply drops or alters anything. However html markup, when rendered for visualization uses a different way to code line breaks. There are very good reasons for that. So what you have to do is "translate" the existing line breaks into html style line breaks.

How to do that depends on the environment you are working under. In general you have to translate line break codes like \n to <br> tags. The php scripting language offers a function for this for example: nl2br()

However take care: this only applies when rendering the text as html markup. This does not apply, when you output the text into a textarea inside a form again to allow changing it for example. In that case you have to preserve the original line breaks just as received.

So what you typically do is: you save the unaltered text input as received. When outputting that text again to a client, say after reading it from a database where you have saved it before, then you know the situation, how the text will be presented. That is when you either translate or leave the existing line breaks as they are.

You could also encode unaltered text containing line breaks by <pre>...</pre> tags, so mark them as to be rendered as preformatted. THis is for example done when displaying source code in html pages.

Generally you just need to add

  • white-space: pre-line; whitespace trimmed to single whitespace or

  • white-space: pre-wrap; all whitespace preserved

to the element's style (CSS), where you want your text rendered with line-breaks.

You keep output in textarea as it is. You would receive input as a string output that string(write to file) that string adding textarea to the input string.

for eg.
<?php
$txt = $_POST["inputstr"];
$txt1 = "<textarea>". $txt ."</textarea>";
$file = fopen("file.html","a+");
fwrite($file, $txt1);
fclose($file);
?>

You can do:

white-space: pre-wrap;
overflow-wrap: break-word;