You can try adapting Re: Pair Tag missing.
In reply to Re: Ensuring HTML is "balanced" by ambrus in thread Ensuring HTML is "balanced" by skx