在字符串php中查找所有模式

时间:2015-03-10 10:11:53

标签: php regex preg-match-all

这是我的字符串。

$str = '"additional_details":" {"mode_of_transport":"air"}"}],"additional_details":"{"mode_of_transport":"air"}"}],"additional_details":"{"mode_of_transport":"air"}"}],';

我想找到所有以"{"开头并以"}"结尾的模式。

我正在尝试这个:

preg_match_all( '/"(\{.*\})"/', $json, $matches );
print_r($matches);

它给了我一个输出:

Array
(
    [0] => Array
        (
            [0] => "{"mode_of_transport":"air"}"}],"additional_details":"{"mode_of_transport":"air"}"}],"additional_details":"{"mode_of_transport":"air"}"
        )

    [1] => Array
        (
            [0] => {"mode_of_transport":"air"}"}],"additional_details":"{"mode_of_transport":"air"}"}],"additional_details":"{"mode_of_transport":"air"}
        )

)

查看数组键1.它还提供一个键中的所有匹配项以及其他详细信息。

我想要一个包含所有匹配项的数组。像

Array
(
    [0] => Array
        (
            [0] => "{"mode_of_transport":"air"}"}],"additional_details":"{"mode_of_transport":"air"}"}],"additional_details":"{"mode_of_transport":"air"}"
        )

    [1] => Array
        (
            [0] => {"mode_of_transport":"air"},
            [1] => {"mode_of_transport":"air"},
            [2] => {"mode_of_transport":"air"}
        )

)

我的模式应该改变什么。

由于

1 个答案:

答案 0 :(得分:1)

您可以使用:

preg_match_all( '/({[^}]*})/', $str, $matches );
print_r($matches[1]);
Array
(
    [0] => {"mode_of_transport":"air"}
    [1] => {"mode_of_transport":"air"}
    [2] => {"mode_of_transport":"air"}
)