0

正規表現の置換を行いたいのですが、見つかるたびに実行したくありません。preg_replace_callback を使用する必要があると思います。そこでランダム チェックを行うだけですが、コールバック関数に複数のパラメータを渡す方法がわかりません。最終的には 2 つ以上の作業が必要になりますが、2 つの作業を行うことができれば、おそらくさらに多くの作業を行うことができます。

たとえば、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 に答える