0

Possible Duplicate:
How to save user-entered line breaks from a TEXTAREA to a database?

When I press an ENTER KEY in a textarea it goes to newline. But when I receive this value from action page it converts to a white space. I want to receive ENTER KEY character as a newline from action page as not a white space. Sample code : this is the HTML code

<form action="go.php" method="POST">
<textarea name="aa" cols="10" rows="10"></textarea>
<form>

Her is the go.php code :

<?php
$txt=$_POST['aa'];
echo $txt;
?>

If I input like "this is me(PRESS ENTER KEY)this is he(PRESS ENTER KEY)". I want to the output as like "this is me(newline)this is he(newline)". But I am getting from go.php like "this is me this is he". Here is no any newline but white space. Please anyone help me. Why it is happen.

Community
  • 1
  • 1
Nirob Hasan
  • 55
  • 1
  • 9
  • 2
    How exactly do you check it's not a new line character? Have you opened the page source? – zerkms Jan 04 '13 at 21:39
  • http://stackoverflow.com/questions/498461/how-to-save-user-entered-line-breaks-from-a-textarea-to-a-database – Jared Jan 04 '13 at 21:41
  • When I print this it always prints a plane string separated by white space. In page source it declare as newline but display as white space. But why I don't know. Please explain me if you know.@zerkms – Nirob Hasan Jan 04 '13 at 21:46
  • Show me some hex or prove you understand what people mean by 'page source' vs browser outputting HTML. – ficuscr Jan 04 '13 at 21:48

2 Answers2

4

I believe you want nl2br. This will insert HTML line breaks before all newlines in a string. If you are planning to store this in a database, you'll need something similar to mysql_real_escape_string() to escape the line breaks.

<?php
echo nl2br("foo isn't\n bar");
?>

The HTML would look like:

foo isn't<br />
 bar

Your code would then look like:

<?php
$txt=$_POST['aa'];
echo nl2br($txt);
?>
Kermit
  • 33,827
  • 13
  • 85
  • 121
  • "you'll need something similar to mysql_real_escape_string()" --- to be clear, you **always** need something "similar to it". Regardless of what and where from you're inserting to DB – zerkms Jan 04 '13 at 21:43
  • @zerkms I am keeping my fingers crossed that the OP is using `PDO` or `mysqli_` functions and prepared statements. – Kermit Jan 04 '13 at 21:44
  • yep. But I meant that your advice is too specific to newlines, while it's always required to escape the input. – zerkms Jan 04 '13 at 21:45
2

You need to use nl2br function to capture and replace newline. Working code below;

<form action="go.php" method="POST">
<textarea name="aa" cols="10" rows="10"></textarea>
<input type="submit" value="s">
</form>
Here is the go.php code :

<?php
$txt=$_POST['aa'];
echo nl2br($txt);
?>
Kad
  • 542
  • 1
  • 5
  • 18