2011-03-31 26 views
4

我有一個這樣的字符串:如何反向引用遞歸正則表達式中的匹配?

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

是否有存儲在正則表達式中間反向引用的方法嗎?或者我必須匹配循環內的每個事件?

謝謝!

回答

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" 
+0

尼斯之一!只有一個字:根據PHP文檔「如果m修飾符是set_」,_ [D]修飾符將被忽略。 – elitalon 2011-03-31 13:32:58

+0

@elitalon哦,好吧,我的錯誤。如果你可以確認它沒有D修飾符,我會編輯我的答案。 – eisberg 2011-03-31 13:34:29

+0

它很好用,謝謝! – elitalon 2011-03-31 13:39:28

相關問題