PHP - split a string of HTML attributes into an indexed array

后端 未结 6 826
后悔当初
后悔当初 2020-12-11 16:20

I\'ve got a string with HTML attributes:

$attribs = \' id= \"header \" class = \"foo   bar\" style =\"background-color:#fff; color: red; \"\';
6条回答
  •  醉梦人生
    2020-12-11 16:49

    You can't use a regular expression to parse html-attributes. This is because the syntax is contextual. You can use regular expressions to tokenize the input, but you need a state machine to parse it.

    If the performance isn't a big deal, the safest way to do it, is probably to wrap the attributes in a tag and then send it through an html parser. Eg.:

    function parse_attributes($input) {
      $dom = new DomDocument();
      $dom->loadHtml("");
      $attributes = array();
      foreach ($dom->documentElement->attributes as $name => $attr) {
        $attributes[$name] = $node->value;
      }
      return $attributes;
    }
    

    You could probably optimize the above, by reusing the parser, or by using XmlReader or the sax parser.

提交回复
热议问题