0

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.

2
  • It looks like it has been through the nl2br() function for a second time. Commented Feb 20, 2012 at 19:52
  • you shouldn't insert the html breaks in to the db, but add them when displaying the article. Commented Feb 20, 2012 at 19:53

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

Do not replace newlines when saving to DB.

2 Comments

From where do you infere he's not escaping the inputs? :o
this also depends on the method used to insert. if he uses prepared statements, there won't be any problem with inserting direct input.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.