简体   繁体   中英

nl2br puts br between html tags

I have a PHP webmail script that I received today message from gmail like this:

$content='
<p>This is just example for MessageContent</
p>Test...<span>Test</span>Test..<span
>Test</span>';

How can I print it with nl2br ?

If I use echo nl2br($content); , I get this result:

<br />
<p>This is just example for MessageContent</<br />
p>Test...<span>Test</span>Test..<span<br />
>Test</span>

So how I can fix this problem?

Personally I think accepting html in a message is bad, and you should strip out any html, why?

Because if you accept html tobe rendered. eg: not using htmlentities($content) from an unknown source then a malicious person could add javascript and XSS attack you, or a dodgy link and CSRF you or even just a 1px image and get your IP.

But if you accept the risk you can just render the message as-is.

<?php 
$content='
<p>This is just example for MessageContent</
p>Test...<span>Test</span>Test..<span
>Test</span>';

//Or at least sanitise abit - Remove all tags except p's an a's
$content = strip_tags($content,'<p><a>');
?>

nl2br is for content you expect to have no html in it.

You could either change $content to

$content='
<p>This is just example for MessageContent</p>
Test...<span>Test</span>Test..
<span>Test</span>';

Or you could just use

echo $content;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM