Skip to content

Instantly share code, notes, and snippets.

Created July 8, 2012 09:20
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
PHP: parse HTML element attributes
function parseAttributes($text) {
$attributes = array();
$pattern = '#(?(DEFINE)
if (preg_match_all($pattern, $text, $matches, PREG_SET_ORDER)) {
foreach ($matches as $match) {
$attributes[$match['n']] = isset($match['v'])
? trim($match['v'], '\'"')
: null;
return $attributes;
//$text = '<a double="" keyword single=\'\'>';
$text = 'double="" keyword single=\'\'';
$res = parseAttributes($text);
Copy link

Hello! Stumbled (actually, googled) upon this. Nice regex; but doesn't parse elements that might have spaces around the '=', as in ' title = "something" ' (any number of spaces around/after the = character).

Copy link

@rickhellewell Try changing line 12
from: (?<n>(?&name))(=(?<v>(?&value)))?#xs';
to: (?<n>(?&name))(\s*=\s*(?<v>(?&value)))?#xs';

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment