tags:

views:

57

answers:

1

I have a paragraph of text below that I want to use an input source. And I want the doSpin() function to take the stream of text and pick one value at random, from each [%group of replacement candidates%].

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

So this sentence, when filtered, could potentially result in any of the following when input...

1) This should make it much more convenient and help reduce duplicate content.

2) This ought make it much faster and help reduce duplicate content.

3) This would make it much easier and help reduce duplicate content.

// So the code stub would be...

$content = file_get_contents('path to my input file');

function doSpin($content)
{
// REGEX MAGIC HERE
return $content;
}

$myNewContent = doSpin($content);

*I know zilch of Regex. But I know what I'm trying to do requires it.

Any ideas?

+2  A: 

Use preg_replace_callback():

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

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

The way this works is that it searches for [%...%] and captures what's in between. That's passed as $matches[1] to the callback (as it is the first captured group). That group is split on | using explode() and a random one is returned using array_rand(),

cletus
Sweet! Thanks cletus. Working it out now.
Scott B
cletus is the man! Worked first time out of the gate!
Scott B