正则表达式:使 'zero or one time occurence' 条件但仅适用于最后一场比赛

Regex: make 'zero or one time occurence' condition but only for the last match

我有这个字符串:

key1:val1;key2:val2;key3:val3

也可以这样写:

key1:val1;key2:val2;key3:val3;

我想 preg_match_all 上面的两个字符串,所以它将 return 相同的数组,如下所示:

匹配 1

Array
(
    [0] => key1
    [1] => key2
    [2] => key3
)

第 2 场比赛

Array
(
    [0] => val1
    [1] => val2
    [2] => val3
)

现在,我正在使用这个正则表达式:

(.*?):(.*?);

不幸的是,它不适用于第一个字符串。我之前尝试使用下面的正则表达式,但结果更糟:

(.*?):(.*?);?

到目前为止,这是我的实验:https://3v4l.org/5HAco .如果有纯PHP函数解决这个问题,我也能接受

$text = "key1:val1;key2:val2;key3:val3";

preg_match_all("/(.*?):(.*?)(?:;|$)/",$text,$matches);
print_r($matches);


$text = "key1:val1;key2:val2;key3:val3;";

preg_match_all("/(.*?):(.*?)(?:;|$)/",$text,$matches);
print_r($matches);

输出:

Array
(
    [0] => Array
        (
            [0] => key1:val1;
            [1] => key2:val2;
            [2] => key3:val3
        )

    [1] => Array
        (
            [0] => key1
            [1] => key2
            [2] => key3
        )

    [2] => Array
        (
            [0] => val1
            [1] => val2
            [2] => val3
        )

)
Array
(
    [0] => Array
        (
            [0] => key1:val1;
            [1] => key2:val2;
            [2] => key3:val3;
        )

    [1] => Array
        (
            [0] => key1
            [1] => key2
            [2] => key3
        )

    [2] => Array
        (
            [0] => val1
            [1] => val2
            [2] => val3
        )

)