如何在递归正则表达式中反向引用匹配项?
我有一个像这样的字符串:
$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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这:
将给
This:
will give