/ Published in: PHP
Parse an attributes string into an array. If the string starts with a tag, then the attributes on the first tag are parsed. This parses via a manual loop and is designed to be safer than using DOMDocument.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
/** * Parse an attributes string into an array. If the string starts with a tag, * then the attributes on the first tag are parsed. This parses via a manual * loop and is designed to be safer than using DOMDocument. * * @param string|* $attrs * @return array * * @example parse_attrs( 'src="example.jpg" alt="example"' ) * @example parse_attrs( '<img src="example.jpg" alt="example">' ) * @example parse_attrs( '<a href="example"></a>' ) * @example parse_attrs( '<a href="example">' ) */ function parse_attrs ($attrs) { if ( '<' === $attrs[0] ) # looks like a tag so strip the tagname $name = ''; # for the current attr being parsed $value = ''; # for the current attr being parsed $mode = 0; # whether current char is part of the name (-), the value (+), or neither (0) $stop = false; # delimiter for the current $value being parsed $space = ' '; # a single space foreach ( $attrs as $j => $curr ) { if ( $mode < 0 ) {# name if ( '=' === $curr ) { $mode = 1; $stop = false; } elseif ( '>' === $curr ) { '' === $name or $arr[ $name ] = $value; break; '' === $name or $arr[ $name ] = ''; # previous name $name = $curr; # initiate new } else { $name .= $curr; } } } elseif ( $mode > 0 ) {# value if ( $stop === false ) { if ( '"' === $curr || "'" === $curr ) { $value = ''; $stop = $curr; } else { $value = $curr; $stop = $space; } } $arr[ $name ] = $value; $mode = 0; $name = $value = ''; } else { $value .= $curr; } } else {# neither if ( '>' === $curr ) break; # initiate $name = $curr; $mode = -1; } } } # incl the final pair if it was quoteless '' === $name or $arr[ $name ] = $value; return $arr; }
URL: http://dev.airve.com/demo/speed_tests/php/parse_attrs.php