2011-10-06 118 views
0

我想做一個正則表達式替換,但是我不想每次都找到它。我認爲preg_replace_callback是我需要使用的,只是做我的隨機檢查,但我不知道如何傳遞迴調函數多個參數。我最終需要兩個以上的工作,但如果我能夠完成兩項工作,我可能會得到更多的工作。帶有多個參數的PHP preg_replace_callback

例如,我想替換50%的時間,其他時間我只是返回找到的東西。這裏有一些我一直在努力的功能,但是不可能。

function pick_one($matches, $random) { 
    $choices = explode('|', $matches[1]); 
    return $random . $choices[array_rand($choices)]; 
} 

function doSpin($content) { 

$call = array_map("pick_one", 50); 
    return preg_replace_callback('!\[%(.*?)%\]!', $call, $content); 
/* return preg_replace_callback('!\[%(.*?)%\]!', 'pick_one($1, 50)', $content); */ 
} 

$content = 'This [%should|ought|would|could%] make it much [%more convenient|faster|easier%] and help reduce duplicate content.'; 

echo doSpin($content).'<br/>'; 

感謝 艾倫

回答

1

您不能直接傳遞多個參數。但是,您可以做的是將該函數改爲類方法,然後創建一個類的實例,該實例的成員屬性設置爲您希望可用於該函數的值(如$random)。

0
<?php 

function pick_one($groups) { 

// half of the time, return all options 
    if (rand(0,1) == 1) { 
    return $groups[1]; 
    }; 

    // the other half of the time, return one random option 
    $choices = explode('|', $groups[1]); 
    return $choices[array_rand($choices)]; 

} 

function doSpin($content) { 

    return preg_replace_callback('!\[%(.*?)%\]!', 'pick_one', $content); 

} 

$content = 'This [%should|ought|would|could%] make it much [%more convenient|faster|easier%] and help reduce duplicate content.'; 

echo doSpin($content).'<br/>';