line breaks in a textarea

前端 未结 13 1619
北荒
北荒 2020-11-27 17:58

I know when saving a textarea you can use the nl2br() or str_replace to change the /n to br tags etc. However what im not sure about how to insert line breaks into a textare

相关标签:
13条回答
  • 2020-11-27 18:13

    PHP Side: from Textarea string to PHP string

    $newList = ereg_replace( "\n",'|', $_POST['theTextareaContents']);
    

    PHP Side: PHP string back to TextArea string:

    $list = str_replace('|', '
', $r['db_field_name']);
    
    0 讨论(0)
  • 2020-11-27 18:17

    Ahh, it is really simple

    just add

    white-space:pre-wrap;
    

    to your displaying element css

    I mean if you are showing result using <p> then your css should be

    p{
       white-space:pre-wrap;
    }
    
    0 讨论(0)
  • 2020-11-27 18:19

    You could use str_replace to replace the <br /> tags into end of line characters.

    str_replace('<br />', PHP_EOL, $textarea);
    

    Alternatively, you could save the data in the database without calling nl2br first. That way the line breaks would remain. When you display as HTML, call nl2br. An additional benefit of this approach is that it would require less storage space in your database as a line break is 1 character as opposed to "<br />" which is 6.

    0 讨论(0)
  • 2020-11-27 18:19

    My recommendation is to save the data to database with Line breaks instead parsing it with nl2br. You should use nl2br in output not input.

    For your question, you can use php or javascript:

    PHP:

    str_replace('<br />', "\n", $textarea);
    

    jQuery:

    $('#myTextArea').val($('#myTextArea').val().replace(@<br />@, "\N"));
    
    0 讨论(0)
  • 2020-11-27 18:20

    Don't do nl2br when you save it to the database. Do nl2br when you're displaying the text in HTML. I can strongly recommend to not store any HTML formatting in the database (unless you're using a rich HTML editor as well, in which case it would be silly not to).

    A newline \n will just become a newline in the textarea.

    0 讨论(0)
  • 2020-11-27 18:25

    This works on me.

     str_replace(array("\r", "\n"), '&#10;', $textareavalue);
    
    0 讨论(0)
提交回复
热议问题