防止损坏的HTML破坏表和页面

My problem is simple - I'm using PHP and grabbing data from a database using mysql. The data im grabbing is a long string of text - sometimes it could have HTML tags in it.

My problem is if the long string of text i'm grabbing contains broken HTML tags, like an anchor tag that doesn't close, it completely destroys the table when I print the string inside the td.

How can I ensure any text inside the td of the table will not break the table (while still rendering the HTML content)?

Sounds like your best bet would be Tidy.

<?php

$fragment = '<p>This is a broken string <a href="blah">on text';

$tidy = new tidy();

$tidy->parseString($fragment,array('show-body-only'=>true),'utf8');
$tidy->cleanRepair();

echo $tidy;