Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looking for PHP function to close HTML tags

Tags:

html

php

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

like image 256
Cyrcle Avatar asked Nov 26 '10 20:11

Cyrcle


People also ask

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.

How do I close HTML 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 /).

Which element is used to close the HTML program?

It has a start tag <html> and an end tag </html> .

Do you need closing PHP tag?

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.


2 Answers

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

like image 134
Paul Dixon Avatar answered Oct 09 '22 23:10

Paul Dixon


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.

like image 23
eyelidlessness Avatar answered Oct 09 '22 23:10

eyelidlessness