简体   繁体   中英

newline character not converting to line break in php text area post

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>

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.

Additional info

<?= $var?> is the short form of <?php echo $var; ?> <?php echo $var; ?>

References

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