繁体   English   中英

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

[英]How can I backreference matches in a recursive regular expression?

我有一个像这样的字符串:

$data = 'id=1

username=foobar

comment=This is

a sample

comment';

我想删除第三个字段中的\\ncomment=... )。

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

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("/[\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"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM