Wednesday, May 29, 2013

Which function in php validate if the string is valid html?

Html validation function in php:
function isValidHtml($string)
{
    $string = "<div>".$string."</div>";
    $start = strpos($string, '<');
    $end = strrpos($string, '>', $start);
    if($start === false && $end === false) {
        return true;
    }
    if ($end !== false) {
        $string = substr($string, $start);
    } else {
        $string = substr($string, $start, $end - $start);
    }
    libxml_use_internal_errors(true);
    libxml_clear_errors();
    $xml = simplexml_load_string($string);
    return count(libxml_get_errors()) == 0;
}
And best way to use this:

if(isValidHtml($strHtml) {
    echo "Valid html";
}

$strHtml = "<table><tr><td>Hi pritom</td></tr><table>"; is FALSE

No comments:

Post a Comment