Re: Checking equal number of <div> and </div> [message #171307 is a reply to message #171283] |
Thu, 30 December 2010 09:04 |
alvaro.NOSPAMTHANX
Messages: 277 Registered: September 2010
Karma:
|
Senior Member |
|
|
El 30/12/2010 2:19, jwcarlton escribió/wrote:
> Can you guys think of a good way for me to check a string to make sure
> there are an equal number of<div (.*)> and</div>? Then, either add
> or remove</div> tags as needed to make them match?
If you don't care about the exact way to fix the mismatched tags, you
can just feed the fragment to an instance of DOMDocument and let it
repair the HTML for you:
<?php
$fragment = '<div style="font-weight: bold">Lorem ipsum <div>dolor sit amet,
<strong><em>luptate</strong></em>. Excepteur proident,
<div class="foo">sunt in culpa</div> officia est laborum.';
$dom = new DOMDocument;
libxml_use_internal_errors(TRUE);
$dom->loadHTML($fragment);
libxml_use_internal_errors(FALSE);
echo $dom->saveHTML();
?>
This prints:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
"http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body><div style="font-weight: bold">Lorem ipsum <div>dolor sit amet,
<strong><em>luptate</em></strong>. Excepteur proident,
<div class="foo">sunt in culpa</div> officia est
laborum.</div></div></body></html>
(There's probably a way to print only the node but I still haven't
figured it out.)
--
-- http://alvaro.es - Álvaro G. Vicario - Burgos, Spain
-- Mi sitio sobre programación web: http://borrame.com
-- Mi web de humor satinado: http://www.demogracia.com
--
|
|
|