Re: Checking equal number of <div> and </div> [message #171336 is a reply to message #171304] |
Thu, 30 December 2010 13:19 |
Jerry Stuckle
Messages: 2598 Registered: September 2010
Karma:
|
Senior Member |
|
|
On 12/30/2010 3:37 AM, jwcarlton wrote:
> On Dec 29, 11:59 pm, Jerry Stuckle<jstuck...@attglobal.net> wrote:
>> On 12/29/2010 8:19 PM, jwcarlton 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?
>>
>>> 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);
>>> }
>>
>> Get an editor that is html aware. It makes your life much simpler.
>>
>
> No, I mean code submitted by the site visitor, not my own code.
OK, that wasn't clear from your first post.
You're not going to be able to correct all of the errors easily, but the
suggestion of using DOM to help is a good one. It will help a lot. But
you don't want to correct the errors - how do you know the correction
itself is correct? You want to just give the user an error message.
However, I'd take a different approach - I'd put in a preview button
(possibly required) which brings up the prospective page in a new window
to let the user verify it looks ok.
--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
jstucklex(at)attglobal(dot)net
==================
|
|
|