Match attribute in a HTML code

This question already has an answer here:

  • How do you parse and process HTML/XML in PHP? 28 answers

  • You have an apostrophe ( ' ) inside your character class but you wanted a quote ( " ).

    myAttr="([^"]*)"
    

    That said, you really shouldn't be parsing HTML with regexes. (Sorry to link to that answer again. There are other answers to that question that are more of the "if you know what you are doing..." variety. But it is good to be aware of.)

    Note that even if you limit your regexing to just attributes you have a lot to consider:

  • Be careful not to match inside of comments.
  • Be careful not to match inside of CDATA sections.
  • What if attributes are bracketed with single quotes instead of double quotes?
  • What if attributes have no quotes at all?
  • This is why pre-built, serious parsers are generally called for.


    The * is a greedy quantifier. You should follow it with a question mark to make it non-greedy:

    myAttr="([^']*?)"
    

    如果您只需要myAttr参数值,请使用以下命令:

    "myAttr="([^"]+)""
    
    链接地址: http://www.djcxy.com/p/29896.html

    上一篇: PHP HTML DOM解析器

    下一篇: 在HTML代码中匹配属性