【问题标题】:preg_* functions matching subpattern with quantifierpreg_* 函数与量词匹配子模式
【发布时间】:2012-02-22 15:24:38
【问题描述】:

我有一个这种形式的正则表达式:

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

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

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

我确实需要某种方法将这些子模式放入一个数组中,这样我就可以将它们传递给 implode 并做我想做的事情。

我在这里遗漏了什么明显的东西吗?

【问题讨论】:

  • 你能给我们展示一些输入字符串的例子吗?

标签: php regex


【解决方案1】:

也许你可以使用

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"
  }
}

【讨论】:

  • 似乎是一个不错的起点,但我将如何影响preg_replace 呢?
  • 我不确定我是否理解。要从初始的$subject var 构建正则表达式模式,我会使用$someVar = '/'.implode('|', $result[1]).'/';,然后使用$someOtherVar = preg_replace($someVar, $someReplacement, $textVar);(我稍微编辑了正则表达式,省略了\r\n)。如果我误解了,我深表歉意。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-09
  • 1970-01-01
  • 2014-07-26
  • 2018-12-10
  • 2011-09-29
  • 2023-03-26
  • 1970-01-01
相关资源
最近更新 更多