Created
October 15, 2011 09:45
-
-
Save rodneyrehm/1289335 to your computer and use it in GitHub Desktop.
extracting attributs from <element attr="value" attr2=val attr3='val'>
This file contains 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 | |
// 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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment