Florin Frătică
Florin Frătică

Reputation: 587

Spacing issue in a html string

On my website I have a section with announcements and now I'm working at a tool which will allow moderators to edit or post new announcements. When a moderator posts an announcement he has a form with an input for the title and a textbox for the content of the article. I use nl2br() function (to insert HTML line breaks before all newlines) in the variable which contains the content of the article. So when I insert an article in the database it will look like this:

First row ...<br />Second row.<br /><br />Regards,<br />Moderators team

When a moderator wants to edit an article I have a textbox which containes the article:

<textarea name="body" maxlength="1000" cols="105" rows="10"><?php echo str_replace('<br />', "\n", $content); ?></textarea>

If the moderator click save button (whithout making any modification) the article becomes something like this (the number of
tags doubles):

First row ...<br /><br />Second row.<br /><br /><br /><br />Regards,<br /><br />Moderators team

Can anybody help me to fix this.

Upvotes: 0

Views: 55

Answers (3)

m0skit0
m0skit0

Reputation: 25873

Do not replace newlines when saving to DB.

Upvotes: 0

Basti
Basti

Reputation: 4042

The problem is nl2br: Inserts HTML line breaks before all newlines in a string http://www.php.net/manual/en/function.nl2br.php

So after nl2br you will have both the newlines and the <br />-tags

Try $content = preg_replace("~\r?\n~", "<br />", $content);, which replaces newlines instead.

Upvotes: 1

BenOfTheNorth
BenOfTheNorth

Reputation: 2872

When you save to the database, don't convert the new lines. If you only convert them when you present in the HTML page on the fly, you won't need to convert them back when you echo out to a textarea instead.

Upvotes: 0

Related Questions