解析PHP中的属性/值列表 [英] Parse a list of attribute/values in PHP
本文介绍了解析PHP中的属性/值列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出具有属性/值对的字符串,例如
Given a string with attribute/value pairs such as
attr1="some text" attr2 = "some other 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.
推荐答案
尝试如下操作:
$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);
产生:
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
)
)
简短说明:
(\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
这篇关于解析PHP中的属性/值列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文