Parse a list of attribute/values in PHP
Given a string with attribute/value pairs such as
attr1="some text" attr2 = "some o开发者_如何学Cther text" attr3= "some weird !@'#$\"=+ text"
the goal is to parse it and output an associative array, in this case:
array('attr1' => 'some text',
'attr2' => 'some other text',
'attr3' => 'some weird !@\'#$\"=+ text')
Note the inconsistent spacing around the equal signs, the escaped double quote in the input, and the escaped single quote in the output.
Try something like this:
$text = "attr1=\"some text\" attr2 = \"some other text\" attr3= \"some weird !@'#$\\\"=+ text\"";
echo $text;
preg_match_all('/(\S+)\s*=\s*"((?:\\\\.|[^\\"])*)"/', $text, $matches, PREG_SET_ORDER);
print_r($matches);
which produces:
attr1="some text" attr2 = "some other text" attr3= "some weird !@'#$\"=+ text"
Array
(
[0] => Array
(
[0] => attr1="some text"
[1] => attr1
[2] => some text
)
[1] => Array
(
[0] => attr2 = "some other text"
[1] => attr2
[2] => some other text
)
[2] => Array
(
[0] => attr3= "some weird !@'#$\"=+ text"
[1] => attr3
[2] => some weird !@'#$\"=+ text
)
)
And a short explanation:
(\S+) // match one or more characters other than white space characters
// > and store it in group 1
\s*=\s* // match a '=' surrounded by zero or more white space characters
" // match a double quote
( // open group 2
(?:\\\\.|[^\\"])* // match zero or more sub strings that are either a backslash
// > followed by any character, or any character other than a
// > backslash
) // close group 2
" // match a double quote
EDIT: This regex fails if the value ends in a backslash like attr4="something\\"
I don't know PHP, but since the regex would be essentially the same in any language, this is how I did it in ActionScript:
var text:String = "attr1=\"some text\" attr2 = \"some other text\" attr3= \"some weird !@'#$\\\"=+ text\"";
var regex:RegExp = /\s*(\w+)\s*=\s*(?:"(.*?)(?<!\\)")\s*/g;
var result:Object;
while(result = regex.exec(text))
trace(result[1] + " is " + result[2]);
And I got the following out put:
attr1 is some text
attr2 is some other text
attr3 is some weird !@'#$\"=+ text
精彩评论