Regex replaces often seem like the solution but they can have a lot of ill side-effects, and not really accomplish what you want. Look into DOMDocument models instead (as some commenters have suggested).
But if you insist on using regex, here's a good post on SO. It uses two passes to accomplish what you want.