willium
willium

Reputation: 2128

Text Area, nl2br, line breaks galore

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!

Upvotes: 3

Views: 3047

Answers (3)

Derek Downey
Derek Downey

Reputation: 1532

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));}

Upvotes: 3

Jonah
Jonah

Reputation: 10091

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 :)

Upvotes: 2

methodin
methodin

Reputation: 6712

nl2br adds br's in front of newlines, but doesnt remove newlines. When you wrap that output in your nl2br_lose it takes:

blahblah<br>\nblahblah

from nl2br and turns it into

blahblah\n\nblahblah

Upvotes: 0

Related Questions