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

发布于 2024-10-28 18:44:08 字数 538 浏览 2 评论 0原文

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

$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'

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

谢谢!

I have a string like this:

$data = 'id=1

username=foobar

comment=This is

a sample

comment';

And I would like to remove the \n in the third field (comment=...).

I have this regular expression that serves my purpose but not so well:

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

My problem is that every match within the second group overwrites the previous match. Thus, instead of having this:

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

I ended up with this:

'...
comment= comment'

Is there any way of storing the intermediate backreferences in a regular expression? Or do I have to match every occurrence inside a loop?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

清欢 2024-11-04 18:44:08

这:

<?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"

This:

<?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);

will give

string(59) "id=1

username=foobar

comment=This is a sample comment"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文