2009-10-22 77 views
3

考虑到与属性/值对一个字符串,如解析属性/值的列表中PHP

attr1="some text" attr2 = "some other text" attr3= "some weird [email protected]'#$\"=+ text" 

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

array('attr1' => 'some text', 
     'attr2' => 'some other text', 
     'attr3' => 'some weird [email protected]\'#$\"=+ text') 

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

+2

你不是解析的标记语言,对? – 2009-10-22 07:50:58

+0

很高兴问这个!不,只需编写我自己的语法,便于在命令行上键入。 – dreeves 2009-10-22 07:57:51

+2

“很容易在命令行上键入”,那么你可能会对http://docs.php.net/getopt – VolkerK 2009-10-22 09:31:27

回答

6

尝试这样:

$text = "attr1=\"some text\" attr2 = \"some other text\" attr3= \"some weird [email protected]'#$\\\"=+ 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 [email protected]'#$\"=+ 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 [email protected]'#$\"=+ text" 
      [1] => attr3 
      [2] => some weird [email protected]'#$\"=+ 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 
+0

感兴趣第三个例子呢? – Gumbo 2009-10-22 08:02:05

+0

是的,我忘了双反斜杠(并仔细检查输出)。我担心自己有时对自己太过自信。谢谢。 – 2009-10-22 08:08:55

+0

php和actionscript之间有什么区别,那就是ecmascript/js btw,处理正则表达式吗?因为这个正则表达式只给出了actionscript中的前两个attrs。 – Amarghosh 2009-10-22 09:01:39

2

编辑:如果该值以反斜线结束。这正则表达式失败像attr4="something\\"

我不知道PHP,但由于正则表达式将是任何语言基本上是相同的,这就是我如何做到了在ActionScript:

var text:String = "attr1=\"some text\" attr2 = \"some other text\" attr3= \"some weird [email protected]'#$\\\"=+ text\""; 

var regex:RegExp = /\s*(\w+)\s*=\s*(?:"(.*?)(?<!\\)")\s*/g; 

var result:Object; 
while(result = regex.exec(text)) 
    trace(result[1] + " is " + result[2]); 

而且我得到了以下出来放:

attR1位是一些文本
attR2位是其他一些文字
attr3是有些不可思议!@#$ \“= +文本

+0

只是一个小小的挑剔:如果该值本身包含一个反斜杠,就像'attr3 =“\\”'(这可能也需要转义),否则它不会起作用当然,这可能永远不会发生,OP没有提到这样的角落案例 – 2009-10-22 08:29:33

+0

嗯你是对的。这不是一个挑剔 - 显然,如果字符串以反斜杠结尾 - 例如'attr4 =“something \\”'' – Amarghosh 2009-10-22 09:03:14