views:

77

answers:

1

I am using php5. I am doing a form, a textarea, where user can send it to his/her friends. But currently, in my textarea form, if i type :

Hello XXX,

Its been a while. How are you?

But when I echo it, it displays

Hello XXX, Its been a while. How are you?

How do I accept the enter button, so that when I display I can display like:

Hello XXX,

Its been a while. How are you?

+6  A: 

There is a function called nl2br() which converts newlines \n to html friendly line breaks. <br> or <br />

It's used like this

echo nl2br("foo isn't\n bar");

This will output

foo isn't<br />bar

Since HTML is markup based, you will need some markup to tell the browser that you want a linebreak.

The reason is that

<p><b>Hello <i>World</i></b></p>

Is the exact same thing as

<p>
<b>
Hello 
<i>
World
</i>
</b>
</p>
Ólafur Waage
+1 Just to extend what you said though: echo nl2br($text);
smack0007
Just remember that you should probably do the `nl2br` stuff when displaying it, not when you save it. That way you won't have to remove all the <br> tags later if you decide to do something different. Or if the user are going to be able to for example edit the text again.
Svish
Good point Svish.
Ólafur Waage
best answer, thanks
You're welcome :)
Ólafur Waage
What if i save to database first, and then display it out? I use mysql_real_escape_string to store in database
Leave the data alone if you save. When you're printing it to the page then you use nl2br().
Ólafur Waage
Thanks, it works. Didnt read Svish comment. It pointed out that issue already.