php > preg_match("@/m(/[^/]+)+/t/?@", "/m/part/other-part/t", $m);
php > var_dump($m);
array(2) {
[0]=>
string(20) "/m/part/other-part/t"
[1]=>
string(11) "/other-part"
}
php > preg_match_all("@/m(/[^/]+)+/t/?@", "/m/part/other-part/t", $m);
php > var_dump($m);
array(2) {
[0]=>
array(1) {
[0]=>
string(20) "/m/part/other-part/t"
}
[1]=>
array(1) {
[0]=>
string(11) "/other-part"
}
}
对于上述示例,我希望捕获同时匹配 /part
和 /other-part
,不幸的是使用正则表达式 /m(/[^/] +)+/t/?
没有像我预期的那样捕获两者。
这个捕获不应该绑定(bind)只匹配这个样本,它应该捕获一个未定义次数的重复捕获组;例如/m/part/other-part/and-another/more/t
更新: 鉴于这是预期的行为,我的问题是如何实现我的这种匹配?
最佳答案
试试这个:
preg_match_all("@(?:/m)?/([^/]+)(?:/t)?@", "/m/part/other-part/another-part/t", $m);
var_dump($m);
它给出:
array(2) {
[0]=>
array(3) {
[0]=>
string(7) "/m/part"
[1]=>
string(11) "/other-part"
[2]=>
string(15) "/another-part/t"
}
[1]=>
array(3) {
[0]=>
string(4) "part"
[1]=>
string(10) "other-part"
[2]=>
string(12) "another-part"
}
}
//编辑
IMO 做你想做的事情的最好方法是使用 @stema 的 preg_match() 并通过 /
展开结果以获得你想要的部分列表。
关于php - Regex量化捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9703823/