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
The strip_tags() function is an inbuilt function in PHP which is used to strips a string from HTML, and PHP tags. This function returns a string with all NULL bytes, HTML, and PHP tags stripped from a given $str. Syntax: string strip_tags( $str, $allowable_tags )
The strip_tags() function strips a string from HTML, XML, and PHP tags. Note: HTML comments are always stripped. This cannot be changed with the allow parameter.
wp_strip_all_tags is a built in wordpress function. Which is used to strip out tags from the given strings. It is a modified function of PHP strip_tags function or an extended version. strip_tags function is used to remove HTML and PHP tags from strings.
stripHtml( html ) Changes the provided HTML string into a plain text string by converting <br> , <p> , and <div> to line breaks, stripping all other tags, and converting escaped characters into their display values.
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>
.
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).
Whitespace is also not allowed in tags: http://php.net/manual/en/function.strip-tags.php (see 2nd note)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With