Reputation: 2276
when i assign a text with newline character and use nl2br function it converts newline to line break but same doesn't happen with textarea post. I want to know why this is happening and also how to convert the newline character from textarea post of a form, to line-break when it is echoed . Below is my code :
<?php
if(isset($_POST['comment'])){
$var = "One line.\nAnother line.";
echo nl2br($var);
echo nl2br($_POST['comment']);
// One line.\nAnother line.
}
?>
<!DOCTYPE html>
<html>
<body>
<form method="post" action="">
<label for="lname">Commment</label><br>
<textarea name="comment" rows="5" cols="40">One line.\nAnother line.</textarea><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Upvotes: 2
Views: 1091
Reputation: 4837
You need to use an actual linebreak in you <textarea>
. \n
wont work there.
nl2br
converts linebreaks to html <br>
.
With php-code you can add a linebreak like this:
<textarea name="comment" rows="5" cols="40">One line.<?= "\n" ?>Another line.</textarea>
Or you spimply write:
<textarea name="comment" rows="5" cols="40">One line.
Another line.</textarea>
If you want to reuse the submitted value:
<textarea name="comment" rows="5" cols="40"><?= htmlentities($_POST['comment']) ?></textarea>
Be careful here, you want to sanitize your user-input with htmlentities($_POST['comment'])
or the user will be able to alter the page.
<?= $var ?>
is the short form of <?php echo $var; ?>
Upvotes: 2