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

前端 未结 7 1893
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-03 16:30

Which function in php validate if the string is html? My target to take input from user and check if input html and not just string.

Example for not html string:

相关标签:
7条回答
  • 2020-12-03 17:09

    Maybe you need to check if the string is well formed.

    I would use a function like this

    function check($string) {
      $start =strpos($string, '<');
      $end  =strrpos($string, '>',$start);
    
      $len=strlen($string);
    
      if ($end !== false) {
        $string = substr($string, $start);
      } else {
        $string = substr($string, $start, $len-$start);
      }
      libxml_use_internal_errors(true);
      libxml_clear_errors();
      $xml = simplexml_load_string($string);
      return count(libxml_get_errors())==0;
    }
    

    Just a warning: html permits unbalanced string like the following one. It is not an xml valid chunk but it is a legal html chunk

    <ul><li>Hi<li> I'm another li</li></ul>
    

    Disclaimer I've modified the code (without testing it). in order to detect well formed html inside the string.

    A last though Maybe you should use strip_tags to control user input (As I've seen in your comments)

    0 讨论(0)
提交回复
热议问题