PHP preg_replace_回调具有多个参数

PHP preg_replace_回调具有多个参数,php,random,preg-replace-callback,Php,Random,Preg Replace Callback,我想做一个正则表达式替换,但我不想每次都找到它。我认为preg_replace_回调是我需要使用的,只是在那里做随机检查,但我不知道如何传递回调函数多个参数。我最终需要两个以上,但如果我能得到两个工作,我可能会得到更多的工作 例如,我想在50%的时间内进行替换,其他时间我只返回找到的内容。这里有几个我一直在使用的函数,但就是不能正确使用它们 function pick_one($matches, $random) { $choices = explode('|', $matches[1]);

我想做一个正则表达式替换,但我不想每次都找到它。我认为preg_replace_回调是我需要使用的,只是在那里做随机检查,但我不知道如何传递回调函数多个参数。我最终需要两个以上,但如果我能得到两个工作,我可能会得到更多的工作

例如,我想在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/>';
函数选择一个($matches,$random){
$choices=explode(“|”,$matches[1]);
返回$random.$choices[array_rand($choices)];
}
函数doSpin($content){
$call=数组映射(“选择一个”,50);
返回preg\u replace\u回调(“!\[%(.*?%\])!”,$call,$content);
/*返回preg\u replace\u回调(“!\[%(.*?%\])!”,“选择一个($1,50)”,$content)*/
}
$content='这个[%should | should | will | could%]可以让它更[%更加方便|更快|更容易%]并有助于减少重复内容。';
echo doSpin($content)。“
”;
谢谢
Allen

您不能直接将多个参数传递给它。但是,您可以做的是将函数改为类方法,然后创建一个类实例,该类的成员属性设置为您希望函数可用的值(如
$random
)。


<?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/>';