簡體   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