Regex for html attributes in php

前端 未结 2 709
谎友^
谎友^ 2021-01-26 02:23

I am trying to parse a string of HTML tag attributes in php. There can be 3 cases:

attribute=\"value\"  //inside the quotes there can be everything also other es         


        
相关标签:
2条回答
  • 2021-01-26 03:15

    Never ever use regular expressions for processing html, especially if you're writing a library and don't know what your input will look like. Take a look at simplexml, for example.

    0 讨论(0)
  • 2021-01-26 03:23

    Give this a try and see if it is what you want to extract from the tags.

    preg_match_all('/( \\w{1,}="\\w{1,}"| \\w{1,}=\\w{1,}| \\w{1,})/i', 
        $content, 
        $result, 
        PREG_PATTERN_ORDER);
    $result = $result[0];
    

    The regex pulls each attribute, excludes the tag name, and puts the results in an array so you will be able to loop over the first and second attributes.

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