我该如何在递归正则表达式中引用先前匹配的内容?

4

我有一个字符串,格式如下:

$data = 'id=1

username=foobar

comment=This is

a sample

comment';

我希望删除第三个字段(comment=...)中的\n

我有一个正则表达式,可以实现我的目的,但效果不是很好:

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

我的问题是第二组内每个匹配都会覆盖前一个匹配。因此,而不是这样:
'...
comment=This is a sample comment'

我最终得到了这个结果:
'...
comment= comment'

有没有办法在正则表达式中存储中间的反向引用?还是我必须在循环内匹配每个出现的情况?

谢谢!

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"

不错!只有一个词:根据 PHP 文档,“如果设置了 m 修饰符,则忽略 D 修饰符”。 - elitalon
@elitalon 哦,好的我的错。如果您可以确认它在没有D修饰符的情况下工作,我会编辑我的答案。 - eisberg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接