preg*函数将子模式与量词相匹配


preg_* functions matching subpattern with quantifier

我有一个如下形式的正则表达式:

/(?:^- (.*)$'r*'n*)+/m

目的是匹配以-[space]开头的一行或多行文本。

除了收集匹配的子模式(.*)时,这一操作很好。只返回最后一个,并且丢失任何以前的子模式匹配(作为索引0的一部分出现在结果数组中)。

我真的需要一些方法来将这些子模式放入数组中,这样我就可以将它们传递给implode,并对它们执行我正在尝试的操作。

我是不是遗漏了一些显而易见的东西?

也许你可以使用

preg_match_all('/^- (.*)'r'n/m', $subject, $result, PREG_PATTERN_ORDER);
var_dump($result);

例如:

<?php
$subject = "- some line
- some content
- some other content
nothing to match over here
- more things here
- more patterns
nothing to match here
";
preg_match_all('/^- (.*)'r'n/m', $subject, $result, PREG_PATTERN_ORDER);
var_dump($result);
?>

结果:

array(2) {
  [0]=>
  array(5) {
    [0]=>
    string(12) "- some line
"
    [1]=>
    string(15) "- some content
"
    [2]=>
    string(21) "- some other content
"
    [3]=>
    string(19) "- more things here
"
    [4]=>
    string(16) "- more patterns
"
  }
  [1]=>
  array(5) {
    [0]=>
    string(9) "some line"
    [1]=>
    string(12) "some content"
    [2]=>
    string(18) "some other content"
    [3]=>
    string(16) "more things here"
    [4]=>
    string(13) "more patterns"
  }
}