2011-03-11 75 views
0

我有一個字符串,它看起來像:PHP解析字符串數組

'- 10 TEST (FOO 3 TEST.BAR 213 BAZ (\HELLO) TEST' 

其他任何字符串相同的格式。我怎麼能得到,FOO,BARBAZ的值。所以,舉例來說,我可以得到一個數組:

'FOO' => 3, 
'BAR' => 213, 
'BAZ' => HELLO 
+2

請解釋字符串模式 – amosrivera 2011-03-11 15:09:17

+0

鍵和值之間的連接背後是什麼樣的邏輯? – powtac 2011-03-11 15:09:35

+0

模式基本上是這樣的:'(CONST值X.CONST值CONST(\ VALUE)X ...)',其中'CONST'是這種情況下的尋寶者 – CalebW 2011-03-11 15:16:43

回答

0

假設既不常數也沒有的值在其中具有空間, 這將對於給定的示例工作:

$str = '(CONST1 value1 X.CONST2 value2 CONST3 (\VALUE3) X...)'; 
preg_match('/\((\S+)\s+(\S+)\s+.*?\.(\S+)\s+(\S+)\s+(\S+)\s+\(\\\\(\S+)\)/', $str, $m); 
$arr = array(); 
for($i=1; $i<count($m);$i+=2) { 
    $arr[$m[$i]] = $m[$i+1]; 
} 
print_r($arr); 

輸出:

Array 
(
    [CONST1] => value1 
    [CONST2] => value2 
    [CONST3] => VALUE3 
) 

解釋

\(   : an open parenthesis 
(\S+)  : 1rst group, CONST1, all chars that are not spaces 
\s+   : 1 or more spaces 
(\S+)  : 2nd group, value1 
\s+.*?\. : some spaces plus any chars plus a dot 
(\S+)  : 3rd group, CONST2 
\s+   : 1 or more spaces 
(\S+)  : 4th group, value2 
\s+   : 1 or more spaces 
(\S+)  : 5th group, CONST3 
\s+   : 1 or more spaces 
\(   : an open parenthesis 
\\\\  : backslash 
(\S+)  : 6th group, VALUE3 
\)   : a closing parenthesis 
+0

完美,謝謝! – CalebW 2011-03-11 16:06:30

+0

不客氣。 – Toto 2011-03-11 16:08:14

3

preg_match是你的朋友:)

+0

我認爲這個答案有點太含糊不清(就像問題一樣)。代替一個具體的建議,這裏有一些工具,可以幫助OP與他的問題:http://stackoverflow.com/questions/89718/is-there-anything-like-regexbuddy-in-the-open-source-world – mario 2011-03-11 15:19:37

1

您想使用的preg_match先搶到的比賽,然後把它們放到一個數組。這會給你你正在尋找什麼:

$str = '- 10 TEST (FOO 3 TEST.BAR 213 BAZ (\HELLO) TEST'; 

preg_match('/FOO (\d+).+BAR (\d+).+BAZ \(\\\\(\w+)\)/i', $str, $match); 

$array = array(
    'FOO' => $match[1], 
    'BAR' => $match[2], 
    'BAZ' => $match[3] 
); 

print_r($array); 

這是假設雖然前兩個值是數字,最後是字的字符。