Re: Checking equal number of <div> and </div> [message #171322 is a reply to message #171283] |
Thu, 30 December 2010 10:53 |
RMP
Messages: 6 Registered: December 2010
Karma:
|
Junior Member |
|
|
Am 30.12.2010 02:19, schrieb jwcarlton:
> 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?
>
> I'm sure that I could do something like this, but PHP is usually
> pretty insightful so I thought there might be a better way:
>
> // typed up for the example; obviously not in use or tested
> $num_opentag = substr_count($text, '<div');
> $num_closetag = substr_count($text, '</div>');
>
> // More closed than open
> if ($num_closetag> $num_opentag) {
> $difference = $num_closetag - $num_opentag;
> $text = preg_replace("/<\/div/i", "", $text, $difference);
> }
>
> // More open than closed
> if ($num_opentag> $num_closetag) {
> $difference = $num_opentag - $num_closetag;
> $text = preg_replace("/<div (.*)>/i", "", $text, $difference);
> }
Can you use DOMXPath::query and run "/descendant-or-self::div" on it?
Or DOMXPath::evaluate with "count(/descendant-or-self::div)" ?
Dunno if it works.
--
And sorry folks for the standalone thread! That was because of Googlegroups.
|
|
|