Tuesday, July 12, 2011

HTML Textarea new line problems with PHP

Many of the beginners face problem with textarea new line. When you save some data in textarea, you may write data beautifully in many lines (by giving {ENTER} key, new line), then when you save the data inside any database, and when you retrive and display that data, you will notice that, all new line startings are lost.

This is because when you press ENTER and give a new line character '\n' character is used inside textarea. But when you print it back, HTML cannot recognize '\n' character. PHP comes with a handy solution for this. There is a function called nl2br(),which replaces all \n characters with <br/> hence all new lines appear in HTML again!
Its not the only solution, you can also use explode function or something similar to find \n and replace it with a <br/> to comply with HTML

echo nl2br("Sachin\nis great");

Sachin<br/>is great

echo nl2br($textarea_data);
will work for textarea data!


  1. hi.. shriram ,, i m the new visitor on your site i was finding blog giving some tutorials ..and i found it out your..

    this post is quite informative...

    Max3logic IT Solutions Pvt. Ltd.
    mlm software in india

  2. Hi Sriram -
    I've got a textarea combined with a preg_match. In trials, I press the ENTER key to start a new line. When I submit the updated form, my preg_match kicks in with a 'character not recognised' warning and the text returns to what was there originally before I started to change things. Basically, the preg_match is not happy with the ENTER being pressed. It's not a DB problem. Can you give me some advice about how to get over this problem ?
    Thanks -

  3. Hi Alan, when i try to execute this line
    I get correct number of elements in $matches array, But i dont know why `` are required, i searched it in Internet and found it. Also sorry dude, im not strong in regular expressions, have to revise them again :) so using proper regular expressions, you can extract the lines i guess. Please try it and we will also be happy if you share the results with us. Thankyou.

  4. thanks for this post..it's really helpful for me as starter..!!