2012-07-12 80 views
1

我想有一個正則表達式,需要PHP:如何將正則表達式替換變量傳遞給函數?

[QUOTE=3] 

並將其轉換爲

<div class="quoted"><div class="quotation-author">Originally written by <strong>AUTHOR_WITH_ID=3</strong></div> 

我得到了它幾乎是正確的,但我不能給一個變量傳遞給獲得的功能作者姓名。

$comment = preg_replace('/\[\s*QUOTE=(\d+)\s*\]/i', '<div class="quoted"><div class="quotation-author">Originally written by <strong>'.get_comment_author((int)'$1').'</strong></div>', $comment); 
+0

'$ 1'是單引號嗎? – MyStream 2012-07-12 21:48:19

+1

@MyStream:是的,我們需要字符串''$ 1''。 – 2012-07-12 21:49:24

+2

不是preg_replace在替換完成之前轉換爲字符串*的第二個參數嗎? – madfriend 2012-07-12 21:49:55

回答

3

更換:

'<div class="quoted"><div class="quotation-author">Originally written by <strong>'.get_comment_author((int)'$1').'</strong></div>' 

不會動態地發生;它被評估,然後作爲參數傳遞。使用preg_replace_callback來調用每個匹配的函數,如下所示:

$comment = preg_replace_callback('/\[\s*QUOTE=(\d+)\s*\]/i', function($m) { 
    return '<div class="quoted"><div class="quotation-author">Originally written by <strong>'.get_comment_author((int) $m[1]).'</strong></div>'; 
}, $comment); 
0

不能使用preg_replace對於這一點,因爲調用get_comment_author(和(int)投)發生之前preg_replace是跑了。

嘗試使用preg_replace_callback

$comment = preg_replace_callback('/\[\s*QUOTE=(\d+)\s*\]/i', function($a){ 
    return '<div class="quoted"><div class="quotation-author">Originally written by <strong>'.get_comment_author($a[1]).'</strong></div>'; 
}, $comment); 

注:根據什麼get_comment_author呢,你不應該需要(int)演員。