在PHP中解析属性/值列表

dre*_*ves 3 php regex parsing

给定具有属性/值对的字符串,例如

attr1="some text" attr2 = "some other text" attr3= "some weird !@'#$\"=+ text"
Run Code Online (Sandbox Code Playgroud)

目标是解析它并输出一个关联数组,在这种情况下:

array('attr1' => 'some text',
      'attr2' => 'some other text',
      'attr3' => 'some weird !@\'#$\"=+ text')
Run Code Online (Sandbox Code Playgroud)

请注意等号周围的不一致间距,输入中的转义双引号以及输出中的转义单引号.

Bar*_*ers 6

尝试这样的事情:

$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);
Run Code Online (Sandbox Code Playgroud)

产生:

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
        )

)
Run Code Online (Sandbox Code Playgroud)

简短说明一下:

(\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
Run Code Online (Sandbox Code Playgroud)