4

私はこのような文字列を持っています:

$data = 'id=1

username=foobar

comment=This is

a sample

comment';

\nそして、3番目のフィールド()のを削除したいと思いcomment=...ます。

私の目的に役立つこの正規表現がありますが、あまりうまくいきません。

preg_replace('/\bcomment=((.+)\n*)*$/', "comment=$2 ", $data);

私の問題は、2番目のグループ内のすべての一致が前の一致を上書きすることです。したがって、これを持っている代わりに:

'...
comment=This is a sample comment'

私はこれで終わった:

'...
comment= comment'

中間の後方参照を正規表現に格納する方法はありますか?または、ループ内のすべてのオカレンスを一致させる必要がありますか?

ありがとう!

4

1 に答える 1

4

これ:

<?php
$data = 'id=1

username=foobar

comment=This is

a sample

comment';

// If you are at PHP >= 5.3.0 (using preg_replace_callback)
$result = preg_replace_callback(
    '/\b(comment=)(.+)$/ms',
    function (array $matches) {
        return $matches[1] . preg_replace("/[\r\n]+/", " ", $matches[2]);
    },
    $data
);

// If you are at PHP < 5.3.0 (using preg_replace with e modifier)
$result = preg_replace(
    '/\b(comment=)(.+)$/mse',
    '"\1" . preg_replace("/[\r\n]+/", " ", "\2")',
    $data
);

var_dump($result);

あげる

string(59) "id=1

username=foobar

comment=This is a sample comment"
于 2011-03-31T12:28:27.580 に答える