Created
January 17, 2015 00:45
-
-
Save taufik-nurrohman/b3b683f28d899e19f830 to your computer and use it in GitHub Desktop.
Regex to Extract HTML Attributes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/*! Based on <https://github.com/mecha-cms/cms/blob/master/system/kernel/converter.php> */ | |
function extract_html_attributes($input) { | |
if( ! preg_match('#^(<)([a-z0-9\-._:]+)((\s)+(.*?))?((>)([\s\S]*?)((<)\/\2(>))|(\s)*\/?(>))$#im', $input, $matches)) return false; | |
$matches[5] = preg_replace('#(^|(\s)+)([a-z0-9\-]+)(=)(")(")#i', '$1$2$3$4$5<attr:value>$6', $matches[5]); | |
$results = array( | |
'element' => $matches[2], | |
'attributes' => null, | |
'content' => isset($matches[8]) && $matches[9] == '</' . $matches[2] . '>' ? $matches[8] : null | |
); | |
if(preg_match_all('#([a-z0-9\-]+)((=)(")(.*?)("))?(?:(\s)|$)#i', $matches[5], $attrs)) { | |
$results['attributes'] = array(); | |
foreach($attrs[1] as $i => $attr) { | |
$results['attributes'][$attr] = isset($attrs[5][$i]) && ! empty($attrs[5][$i]) ? ($attrs[5][$i] != '<attr:value>' ? $attrs[5][$i] : "") : $attr; | |
} | |
} | |
return $results; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Test Code