I have a problem that looks like this:
My string of text looks like so:
<div>
content
<div>
<div>
content
<div>
</div>
</div>
If you notice I’m missing some divs and this risks breaking my theme when I use this content elsewhere.
What would be the best way to go about solving a problem like this. This is what I have on my own but often it is not good enough. This function attempts to solve the problem by not fixing it, yet instead box it in to prevent the possibility that the broken html will break my other html.
function ($string)
{
$div_open = substr_count($string, "<div");
$div_close = substr_count($string, "</div>");
while ($div_close<$div_open)
{
$string = "$string</div>";
$div_close = substr_count($string, "</div>");
if ($i>1000){echo 'pop 3'; exit;}else{$i++;}
}
while ($div_close>$div_open)
{
$string = "<div>$string";
$div_open = substr_count($string, "<div");
if ($i>1000){echo 'pop 4 '; exit;}else{$i++;}
}
return $string;
}
Is there a better way?
Very solid way to clean your HTML output is to use Tidy extension of PHP.
You can do the following:
and your HTML output will look like:
There’s also quite many settings of Tidy you can play with, so basically it’s up to you how your output is gonna look like.
A disadvantage would be that Tidy sometimes likes to do things that you really don’t want to see. If your HTML code isn’t really messed up badly, I recommend it.