Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php strip_tags: allows <br />?

Tags:

php

strip

tags

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

like image 417
Run Avatar asked Sep 25 '10 13:09

Run


People also ask

What is strip_tags function in PHP?

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 )

How to remove HTML tags using PHP?

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.

How do I remove HTML tag from string in Wordpress?

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.

What is strip HTML?

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.


3 Answers

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>.

like image 75
Randy the Dev Avatar answered Oct 17 '22 06:10

Randy the Dev


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).

like image 25
bobince Avatar answered Oct 17 '22 07:10

bobince


Whitespace is also not allowed in tags: http://php.net/manual/en/function.strip-tags.php (see 2nd note)

like image 41
Ronald Avatar answered Oct 17 '22 07:10

Ronald