PHP:preg_match_all() - 除数组

时间:2016-01-20 16:09:19

标签: php arrays regex preg-match

我有以下代码:

$str = '{"ok1", "ok2"}, 
        {"ok3", "ok4"}, 
        {"ok5", "ok6"}';

preg_match_all('/"([^"]*)"/', $str, $matches);

print_r($matches[1]);

输出: Array ( [0] => ok1 [1] => ok2 [2] => ok3 [3] => ok4 [4] => ok5 [5] => ok6 )

它工作得很完美,但我想把它变成array1,array2和array3。因此,它将根据{}

中的标记划分数组

即。

 `array1` will be  `array("ok1", "ok2")`;
 `array2` will be  `array("ok3", "ok4")`; 
 `array3` will be  `array("ok5", "ok6")`; 

2 个答案:

答案 0 :(得分:1)

有点矫枉过正,但你可以确实用两个正则表达式实现它(如果这不是一些JSON代码):

<?php 
$string = '{"ok1", "ok2"}, {"ok3", "ok4"}, {"ok5", "ok6"}';
$regex = '~(?<=}),\s~';
$result = array();
$parts = preg_split($regex, $string);
foreach ($parts as $part) {
    preg_match_all('~"(?<values>[^"]+)"~', $part, $elements);
    $result[] = $elements["values"];
}
echo $result[0][1]; // ok2
?>

答案 1 :(得分:1)

Jan的答案非常好,我只是在这里发布我的另一种方法来解决使用正则表达式的问题 - 而不是从他的答案中删除。

如果您有这样的字符串:

$output_array = array();
$str = '{"ok1", "ok2", "ok9", "ok11"}, 
        {"ok3", "ok4"}, 
        {"ok5", "ok6", "ok99"}';

然后你可以查找所有花括号集并将它们存储到数组中:

preg_match_all('~\{.*?\}~', $str, $matches);

最后,只需循环遍历每组括号,并匹配出现在引号中的每组数据。然后将这些匹配添加到输出数组。

foreach ($matches[0] AS $set) {
    preg_match_all('~".*?"~', $set, $set_matches);
    $output_array[] = $set_matches[0];
}

print_r($output_array);

那会给你一个像这样的数组:

Array
(
    [0] => Array
        (
            [0] => "ok1"
            [1] => "ok2"
            [2] => "ok9"
            [3] => "ok11"
        )

    [1] => Array
        (
            [0] => "ok3"
            [1] => "ok4"
        )

    [2] => Array
        (
            [0] => "ok5"
            [1] => "ok6"
            [2] => "ok99"
        )

)