How nl2br user works with htmlspecialchars in phpmysql

How to insert nl2br function using htmlspecialchars ? I have a website where input is from textarea, and nl2br used to convert the next line to a paragraph. When I tried with htmlspecialchars , I got the result below. Here I wrote three words "test" in textarea and saved to the database. I use htmlspecialchars to prevent html injections, but due to this function the nl2br function nl2br not work. Can you tell me how to solve this problem?

 test<br/>test<br/>test<br/> 
+6
source share
4 answers

yo do:

 htmlspecialchars(nl2br($text)); 

you need:

 nl2br(htmlspecialchars($text)); 
+8
source

Call nl2br after calling htmlspecialchars :

 echo nl2br(htmlspecialchars($the_text)); 
+3
source

About using the correct order,

htmlspecialchars (nl2br ($ string)); will give the result that you describe. nl2br (htmlspecialchars ($ string)); will give the result you want.

+2
source

nl2br

Inserts HTML line breaks before all newlines in a line

htmlspecialchars

Convert special characters to HTML objects

 $text = "Hello \n World"; $unexpected_result = htmlspecialchars(nl2br($text)); // => "Hello &lt;br /&gt; World" $expected_result = nl2br(htmlspecialchars($text)); // => "Hello <br/> World" 

... therefore we need to use htmlspecialchars before nl2br

+1
source

Source: https://habr.com/ru/post/894100/


All Articles