Improved HTML markup replacement

Fixed potential bugs.