This sounds like the perfect job for a stack or LIFO. A similar exercise is parenthesis matching. Push tags that you find onto the stack. If you encounter a closing tag, pop the stack and compare what you popped to the current closing tag. Mismatched tags are bad HTML but rarely harmful. If, at the end, you have leftover tags, you have unclosed tags. Beware! Old standards allow this in a limited form, most notably for <p> tags among others. You'd need to read up on the standards to see which are acceptable and which are not.
AgentM Systems nor Nasca Enterprises nor
Bone::Easy nor Macperl is responsible for the
comments made by
AgentM. Remember, you can build any logical system with NOR.