Use stack. When you see an open tag, push it on to the stack, see a close tag, compare it with the last element in the stack, match than pop it out, otherwise deal with the error. If the tag is self-closed, either don't push it, or push then pop, depends on the way you treat the content.