I wouldn't do this with regular expressions, the dang things are hard enough to work with at the best of times, without trying to get them to do stuff like this! You could just use a regular array as a sort of stack, and process the tags one by one. You can use a small regular expression to extract one tag at a time like this:
/\<([a-z]+)[\ \"a-z0-9\/]\>/i
The regex will need tweaking depending on what will exist in a given tag.
This will recognise a tag (use the $matches array to extract the tag name found in the brackets), and using a stack you can then close of the tags as you need. However, if your HTML code is going to contain any closing tags, you'll need to look out for these.
If your code is meant to be used as some sort of valid code fixer, then you probably have a major headache infront of you.