Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ensure all tags are closed php

Tags:

html

php

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?

like image 221
Chris Sobolewski Avatar asked Mar 25 '11 13:03

Chris Sobolewski


People also ask

How do you check if all HTML tags are 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.

How do I close HTML tags in 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. Note: This function is binary-safe.

Does PHP require closing tag?

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.

How do I close open tags?

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


1 Answers

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; 
?>
like image 114
Jan Hančič Avatar answered Oct 19 '22 19:10

Jan Hančič