I'm looking for a PHP function to close HTML tags.
I'm building a site that has admins entering content in a "WYSIWYG" editor. Some of the screens will only show part of the content and then prompt the user to "click for more". So I need to be able to close all the HTML tags that were opened in the part of the content that is initially displayed.
Thanks for any help
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.
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 /).
It has a start tag <html> and an end tag </html> .
For files that contain only PHP code, the closing tag ("?>") is never permitted. It is not required by PHP, and omitting it´ prevents the accidental injection of trailing white space into the response.
I think you can do this by running the HTML through something like tidy. An extension for this is available in PHP.
For example, suppose you had a fragment like this
<h1>hello
<table>
<tr><td>and you cut the text right here... </t
Thorny! Dangling tags and a truncation in mid-tag!
Here's what you'd get back
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html>
<head>
<meta name="generator" content=
"HTML Tidy for Linux/x86 (vers 25 March 2009), see www.w3.org">
<title></title>
</head>
<body>
<h1>hello</h1>
<table>
<tr>
<td>and you cut the text right here...</td>
</tr>
</table>
</body>
</html>
Pretty impressive! Now all you need to do is just extract the repaired fragment back out of the body element.
See also the answers to PHP: Truncate HTML, ignoring tags
You should be able to do this with PHP's native DOM library. Creating a DOMDocument
object with the truncated contents, then converting it back to a string will result in a normalized DOM tree not unlike what a browser would produce with a DocumentFragment
.
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