tags:

views:

132

answers:

3

Hi,

How it is possible to allow <br /> in strip_tags() or any way I can get around to it?

<?php
$text = '<p>Test <br />paragraph.</p><!-- Comment --> <a href="#fragment">Other text</a>';
echo strip_tags($text);
echo "\n";

// Allow <p>, <a>, <br />
echo strip_tags($text, '<p><a><br />');
echo "\n";

// Allow <br /> only
echo strip_tags($text, '<br />');
?>

result:

Test paragraph. Other text
<p>Test paragraph.</p> <a href="#fragment">Other text</a>
Test paragraph. Other text

Thanks, Lau

+3  A: 

Don't use a self-closing tag name? echo strip_tags($text, '<br>');

The strip_tags() function's allowable_tags argument takes the allowed tags in the form <tagname> The reason your code didn't work was because you used <br /> instead of <br>.

Andrew Dunn
thanks! i should had thought of that! lol
lauthiamkok
A: 

Ya you can mix one or more tag to be striped same time.

string strip_tags ( string $str [, string $allowable_tags ] )

check documentation

if you want to strip new line as well solution will be before stripping you can use nl2br

so

echo strip_tags(nl2br($text), '<br>');
JapanPro
thank you! I should had thought of that! lol
lauthiamkok
+2  A: 

strip_tags is not intended as a security measure, and using it with allowable_tags is definitely insecure, as it'll let through event handler and other harmful attributes.

If you want to allow user input with a few whitelisted elements and attributes you'll need to use a HTML-sanitising library with a proper HTML parser. See for example HTML purifier.

It's usually better for user comments not to give the user control over the HTML markup at all, but instead to accept raw text, HTML-escape it on output, and do replacements to generate markup from text (eg: \n -> <br>, \n\n -> </p><p>, link detection).

bobince