4

我有这个例子:

This is a simple test text.
Yet another line.
START: This is the part that
 needs match.
This part does not need
 capture.
Wherever else text.

我想匹配这部分:

START: This is the part that
     needs capture.

关键是我知道它在START:那里,它以一个新行结束,它后面只有一个空格。

我尝试了很多组合,从:START: (.*?)

我已经使用了 \r 和任何我能想到的只有在没有空格的情况下才能匹配的东西。

我不是菜鸟问,因为我很懒。我花了几个小时才问。

4

2 回答 2

12

这个怎么样:

preg_match(
    '/^         # Start of line
    START:\     # Match "START: "
    .*          # Match any characters except newline
    \r?\n       # Match newline
    (?:         # Try to match...
     ^          # from the start of the line:
     \ +        #  - one or more spaces
     .*         #  - any characters except newline
     \r?\n      #  - newline
    )*          # Repeat as needed/mx', 
    $subject)

这假定所有行都以换行符结尾。

于 2012-09-27T07:34:19.220 回答
1

此代码将与您的示例测试一起正常工作。

解决方法是替换 preg_match 之前的新行(之后恢复!)和正则表达式末尾的 Ungreedy 修饰符(U)

<?php

$token = '#####';

$text = <<<TXT
This is a simple test text.
Yet another line.
START: This is the part that
 needs match.
This part does not need
 capture.
Wherever else text.
TXT;

$text = str_replace("\n", $token, $text);

if (preg_match('/(?P<match>START:(.)*)(' . $token . '){1}[^ ]+/Uu', $text, $matches))
{
    $match = str_replace($token, "\n", $matches['match']);
    var_dump($match);
}

$text = str_replace($token, "\n", $text);

输出将是:

string(42) "START: This is the part that
 needs match."
于 2012-09-27T07:40:49.683 回答