php - Regex量化捕获

标签 php regex

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/

相关文章:

javascript - 为什么我的 angularjs 多选界面不起作用?

magento - 将产品默认图片更新为图片库中的第一张图片

php - 检查字符是否在 PHP 中的单词中

正则表达式匹配多个整个单词

javascript - JavaScript 中的动态与内联 RegExp 性能

php - 在存储过程之外提交事务

php - 使用 fsockopen 连接到服务器 - 连接被拒绝

php - 从网站(php)运行时如何停止python脚本

java - 用于检测 "[blablablabla]"等内容的正则表达式

regex - sed中的“-n”实际上是什么意思?