public
Created

extracting attributs from <element attr="value" attr2=val attr3='val'>

  • Download Gist
extract-attributes.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
<?php
 
// extracting attributes
// http://stackoverflow.com/questions/7776469/preg-match-with-name-being-last-in-input
 
$expected = array(
'value' => 'joe',
'type' => 'hidden',
'name' => 'firstname',
);
 
$sources = array(
'<input value="joe" type="hidden" name="firstname">',
'<input value="joe" name="firstname" type="hidden">',
'<input name="firstname" type="hidden" value="joe">',
'<input name=firstname type="hidden" value=\'joe\'>',
);
 
// http://www.php.net/manual/en/reference.pcre.pattern.syntax.php
$pattern = "/\s+(?<name>[a-z0-9-]+)=(((?<quotes>['\"])(?<value>.*?)\k<quotes>)|(?<value2>[^'\" ]+))/i";
 
foreach ($sources as $source) {
$result = array();
preg_match_all($pattern, $source, $matches, PREG_SET_ORDER);
 
foreach ($matches as $match) {
$result[$match['name']] = $match['value'] ?: $match['value2'];
}
var_dump($source, $result == $expected);
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.