I have a <textarea>
where I am allowing user content to be submitted. I would like to allow a couple tags such as <b>
, <i>
,<blockquote>
, and <del>
. However, since the content will be displayed in the page, I have to ensure that there are no unclosed tags.
I know I can use strip_tags($textarea, '<b><i><blockquote><del>')
, but how can I then ensure that all the remaining tags are properly closed?
The <meta> element clearly isn't closed where it should be, and the result is that the <title> element won't be recognised in browsers. But give that markup to the W3C validator and it will tell you that it validates.
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. Note: This function is binary-safe.
Note: The closing tag of a PHP block at the end of a file is optional, and in some cases omitting it is helpful when using include or require, so unwanted whitespace will not occur at the end of files, and you will still be able to add headers to the response later.
An opening tag begins a section of page content, and a closing tag ends it. For example, to markup a section of text as a paragraph, you would open the paragraph with an opening paragraph tag <p> and close it with a closing paragraph tag </p> (closing tags always proceed the element with a /).
You could use Tidy. It will clean and sanitize your HTML.
This comment, on php.net, address your problem and shows how to solve it: http://www.php.net/manual/en/tidy.examples.basic.php#89334
Cleaning an html fragment (OO support seems to half-arsed for now)
This will ensure all tags are closed, without adding any html/head/body tags around it.
<?php
$tidy_config = array(
'clean' => true,
'output-xhtml' => true,
'show-body-only' => true,
'wrap' => 0,
);
$tidy = tidy_parse_string($html_fragment, $tidy_config, 'UTF8');
$tidy->cleanRepair();
echo $tidy;
?>
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