سؤال

When a user save a text from a textarea:

bfajsdb fkjasdfasjkdfasdfasdf asdf asdf sdf

asdfasdfasdfasdf asd asdf asdf 

sdfasdfasdf

from a textarea using nl2br_except_pre function in codeignter it saves it in the database like :

bfajsdb fkjasdfasjkdfasdfasdf asdf asdf sdf
<br>
asdfasdfasdfasdf asd asdf asdf 
<br>
sdfasdfasdf

It is nice for output in div or p tags. or in html output in general.

However, when repoopulating inside textarea again it shows the
tags, which is ugly and confuse the user.

How can I sanitize the output before repopulating the saved value from database so it looks in the textarea like this:

bfajsdb fkjasdfasjkdfasdfasdf asdf asdf sdf

asdfasdfasdfasdf asd asdf asdf 

sdfasdfasdf

and not like this:

bfajsdb fkjasdfasjkdfasdfasdf asdf asdf sdf
<br>
asdfasdfasdfasdf asd asdf asdf 
<br>
sdfasdfasdf
هل كانت مفيدة؟

المحلول

Well, the crude answer will be 'just use strip_tags':

$raw_textarea = 'bfajsdb fkjasdfasjkdfasdfasdf asdf asdf sdf
<br>
asdfasdfasdfasdf asd asdf asdf 
<br>
sdfasdfasdf';

$clean_textarea = strip_tags($raw_textarea);
echo $clean_textarea;

But, in fact, there's much more to that: perhaps you need to worry about sanitizing your output, not just cleaning out irrelevant tags. I suggest reading this discussion on that topic.

نصائح أخرى

Don't save nl2br() data in your database; you should aim to store data rather than html in your db.

Apply nl2br() to your database value upon rendering in your view where necessary. Textarea fields wouldn't need the nl2br() treatment btw.

Of course you should also apply htmlspecialchars() before nl2br() when you output it.

Try nl2br php function

It will make your desired output.

Yes, this is right. If you are using nl2br function while displaying the data, it will work.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top