0

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

谢谢艾伦

4

2 回答 2

1

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

于 2011-10-06T02:30:05.070 回答
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/>';
于 2011-10-06T02:34:09.817 回答