How to save line breaks from a textarea to the database? [duplicate]

7

I have textarea and would like to save the line breaks made by the user in the database. For example , the user writes the following:

"Lorem Ipsum.
Is simply.
Dummy text.
Of the printing.
And typesetting."

But in the database, it is saved as:

  

"Lorem Ipsum. Is simply. Dummy text. Of the printing. And typesetting."

I would like it to be written with the line breaks made in textarea. How can I do this using PHP ?

    
asked by anonymous 06.01.2017 / 20:08

4 answers

5

You can use nl2br , to test you can do:

<form method="POST">
    <textarea name="test"></textarea>
    <input type="submit">
</form>
<?php
echo nl2br($_POST['test']);

You'll get a warning before the first attempt because you have not done a post yet, after submitting it will already be ok.

    
06.01.2017 / 20:12
2

You can use the nl2br () :

Ex:

echo nl2br("Essa\r\neh\n\ruma\nstring\r");

Output:

Essa<br />
eh<br />
uma<br />
string<br />

Or put the text to be written between the tags <pre></pre> .

Ex:

<pre>
Linha 1.
           Linha 2 esta a direita da linha 1.
           Linha 3 esta alinhada com a linha 2.
</pre>

See more at W3C Wiki - HTML / Elements / pre

    
06.01.2017 / 20:17
1

Do not use nl2br to save in the bank so as not to dirty the bank with html. you can use it at any time on the screen. Unless your intention is to save html to the database, for example, if you are going to save the contents of a WYSIWYG editor.

    
07.01.2017 / 13:38
-2

I know that maybe it's not in the scope of the question, but it's also a way to solve your problem and still implement a more elegant solution.

Use a TextEditor.

In addition to giving you better security, it also allows you to customize the text. Notice that Stackoverflow itself uses the Texteditor.

There are several types of texteditor on the market, see which fits best for your solution and implements. It may be a bit tricky at first, but you will see that the final solution will be much more elegant.

    
07.01.2017 / 15:13