2011-03-11 80 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); 

这是假设虽然前两个值是数字,最后是字的字符。