简体   繁体   中英

Store the line break from textarea , store to database and show on frontend?

Currently I am working on storing textarea paragraph

<textarea rows="10"></textarea>

I can save the whole content but the problem is it does not include line breaks. I wonder what is the best practice of storing the space/line break from the textarea to database. Also, I need to prevent the user from inserting the inside the textarea.

Is it good parctice ?

e.g.
text=replace(text,"/n","<br>")
text=replace(text," ","&nbsp;") 
text=replace(text,"<script>","") 
text=replace(text,"</script>","") 

Thanks

It does store linebreaks, but when you do output in HTML you can not see it. Use nl2br() function to convert linebreaks into <br /> tag so you can see linebreaks in HTML.

If you want to prevent some HTML tags in the text - use strip_tags() function (you can allow some tags if you wish). And don't forget to use mysql_real_escape_string() or something like this to escape data.

Another options except what Paul suggested are

  1. Use the <pre> tag that actually brakes lines with /n .. that way you don't need to manipulate the text.. you will have to custom style the <pre> block as the defaults resembles console fonts and styles.
  2. Use a disabled tag with custom styling to avoid manipulation of the text.

here is a fiddle to display both examples (I used JS to inject the values but it should work when you inject the from PHP as well): http://jsfiddle.net/BvynR/

<pre id="pre">   
</pre>
<textarea id="textarea" disabled="disabled">
</textarea>


var str = "Hello I'm a pre-formatedt text \nand this is a new line";
$("#pre").html(str);

$("#textarea").text(str);


#pre
{
    font-family: verdana,helvetica,arial,sans-serif;
    font-size:1em;
}

#textarea
{
    font-family: verdana,helvetica,arial,sans-serif;
    font-size:1em;
    width:100%;
    border:none;
    background: none;
}

If it was me, I would be inserting the data in exactly as you received it from the user. This is because you might need to pull out that data sometime in the future, and not have it in HTML - eg for a report or putting into a spreadsheet or someething else.

Of course you then need to be extra careful about pulling data out and displaying it on the page - but you should be doing that anyway, and you don't want to be relying on your input sanitation being perfect - you might need to replace/update it in the future.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM