我想做一个正则表达式替换,但我不想每次找到它时都这样做。我认为 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/>';
谢谢艾伦