You are getting around to writing a complete parser, your original script seemed aimed at not converting specified tags.
You will need to make a list of opening tags you encounter, and on encountering a closing tag, pop tags off your array converting them unless they match the closing tag.
On encountering end of file, you will have to pop all remaining tags off and convert them.
Have a go at writing that yourself and when you hit an issue get back to us.