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

我有一个像这样的字符串:
$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'
有没有办法将中间反向引用存储在正则表达式中?或者我是否必须匹配循环内的每个事件? 谢谢!     
已邀请:
这个:
<?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("/[rn]+/", " ", $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("/[rn]+/", " ", "2")',
    $data
);

var_dump($result);
会给
string(59) "id=1

username=foobar

comment=This is a sample comment"
    

要回复问题请先登录注册