2009-10-22 76 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