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 (後に復元される!) の前の新しい行と、正規表現 (U) の最後にある Ungreedy 修飾子を置き換えるトークンです。

<?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 に答える