[英]Regex: make 'zero or one time occurence' condition but only for the last match
I have this string: 我有这个字符串:
key1:val1;key2:val2;key3:val3
It could be written like this too: 也可以这样写:
key1:val1;key2:val2;key3:val3;
I want to preg_match_all both of strings above so it will return same array like this: 我想要上面的两个字符串都为preg_match_all,因此它将返回相同的数组,如下所示:
MATCHES 1 比赛1
Array
(
[0] => key1
[1] => key2
[2] => key3
)
MATCHES 2 比赛2
Array
(
[0] => val1
[1] => val2
[2] => val3
)
Right now, I'm using this regex: 现在,我正在使用此正则表达式:
(.*?):(.*?);
Unfortunately, it don't work for the first string. 不幸的是,它不适用于第一个字符串。 I tried using regex below before, but the result was worse: 我之前尝试过使用正则表达式,但结果更糟:
(.*?):(.*?);?
Here is my experiment so far: https://3v4l.org/5HAco . 到目前为止,这是我的实验: https : //3v4l.org/5HAco 。 If there is a pure PHP function to solve this problem, I can accept it too. 如果有一个纯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);
Output: 输出:
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
)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.