test
test

Reputation: 115

how to user nl2br function with htmlspecialchars in phpmysql

How to insert nl2br function with htmlspecialchars? I have a site where input is taken from textarea and nl2br is used to convert next line to a paragraph. When I tried with htmlspecialchars I got the below output. Here I wrote three 'test' words in textarea and saved in database. I am using htmlspecialchars to prevent html injections but because of this function nl2br function is not working. Can you tell be how to work around this problem?

test<br/>test<br/>test<br/>

Upvotes: 8

Views: 5504

Answers (4)

Az.Youness
Az.Youness

Reputation: 2652

nl2br

Inserts HTML line breaks before all newlines in a string

htmlspecialchars

Convert special characters to HTML entities

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

... That's why we need to use use htmlspecialchars before nl2br

Upvotes: 2

Johan
Johan

Reputation: 1557

It's about using the right order,

htmlspecialchars(nl2br($string)); will produce the result you describe. nl2br(htmlspecialchars($string)); will produce the result you wish.

Upvotes: 2

RiaD
RiaD

Reputation: 47620

yo do:

htmlspecialchars(nl2br($text));

you need:

nl2br(htmlspecialchars($text));

Upvotes: 12

Delan Azabani
Delan Azabani

Reputation: 81384

Call nl2br after you call htmlspecialchars:

echo nl2br(htmlspecialchars($the_text));

Upvotes: 4

Related Questions