如何检查textarea是否为HTML? [重复]

This question already has an answer here:

How do I check if what was written in the textarea by the user is valid HTML? It could be with either PHP or Javascript.

</div>

In php, it would be quite simple:

if($text!=htmlspecialchars($text))
{
    echo 'This contains HTML tags!!';
}

Of course, this means an ampersand would be valid, so you could also do something like

function hasHtml($string) {
    if ( $string != strip_tags($string) )
        return true;
}

You can use John Resig's html parser for the Javascript solution, or do something like this:

function is_html(string)
{
  return string.match("/<[^<]+>/").length != 0;
}

You could post the contents to a html validation script or online service and show the result.

You may also want to investigate the PHP DOMDocument class which has some validating functionality.

in js, it's easy since it has an HTML parser built-in:

function isHTML(str){
  var div=document.createElement("div");
  div.innerHTML=str;
  return div.children.length>0;
}

note that this will validate that there is some well-formed html, or html that quirks into well-formed html. strict validity is another matter, and only FireFox lets you ajax view-source: urls to sniff for error title attribs in the gecko html display markup. Other browsers will need a server-side proxy to the w3 validator, or a on-site html validation service provided by your own server.