Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Text Area, nl2br, line breaks galore

Tags:

html

php

I have a textarea, where the users enters text (with as many returns as they want), and I take that value, insert it into a database, and then update the textarea's value with the one in the database.

<textarea maxlength="500" cols="110" name="description" rows="15"><?php if(isset($newDesc)) echo snl2br_lose(nl2br($newDesc)); else echo nl2br_lose(nl2br($user->desc));?></textarea>

is my html. The issue i'm having is, whilst submitting the value and inserting it into the database works, it doubles the amount of linebreaks when it fills the value of the textarea. So if they type

Hey line break Foobar

it will make the textarea's value

Hey line break line break Foobar

function nl2br_lose($string) { 
     return str_replace('<br/>', '&#013;', str_replace('<br />', '&#013;',str_replace('<br>', '&#013;',str_replace('<br >', '&#013;',$string)))); 
 } 

is the function i'm using to turn nl2br into textarea "returns". However, if I take out nl2br_lose from the return, it only has one
, so the issue must be there. I've been having trouble with this for the better part of today.

Thanks in advance!

like image 965
willium Avatar asked Nov 20 '25 20:11

willium


2 Answers

in nl2br_lose:

`return preg_replace("/<br\s?\/?>/", '', $string); //removes <br>, <br/>, <br />, <br >`

of course, it exchanges readibility for simplicity. the other option is to write a function to call instead of nl2br:

function stripnl2br($string) {return str_replace("\n", '', nl2br($string));}
like image 112
Derek Downey Avatar answered Nov 23 '25 10:11

Derek Downey


You need to just replace the br matches with nothing, because nl2br does not remove whitespace.

return str_replace(array(
        '<br/>',
        '<br />',
        '<br>',
        '<br >'
    ), '', $string);

P.S. You might want to change the name from nl2br_lose to br2nl :)

like image 41
Jonah Avatar answered Nov 23 '25 09:11

Jonah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!