如何在递归正则表达式中反向引用匹配?

时间:2011-03-31 12:11:20

标签: php regex grouping backreference

我有一个这样的字符串:

$data = 'id=1

username=foobar

comment=This is

a sample

comment';

我想删除第三个字段\n中的comment=...

我有这个正则表达式符合我的目的但不太好:

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

我的问题是第二组中的每个匹配都会覆盖前一个匹配。因此,而不是这个:

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

我最终得到了这个:

'...
comment= comment'

有没有办法在正则表达式中存储中间反向引用?或者我是否必须匹配循环中的每个事件?

谢谢!

1 个答案:

答案 0 :(得分: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"