- substr_count: documentation ( source)
- preg_replace_callback: documentation ( source)
- mt_rand: documentation ( source)
- explode: documentation ( source)
<?php
$sentence = '{Please|Just} make this {cool|awesome|random} test sentence {rotate {quickly|fast} and random|spin and be random}';
function sentence_spinning($str)
{
while (@$count !== 0)
{
$str = preg_replace_callback('#\{([^{}]*)\}#', function($matches)
{
return explode('|', $matches[1])[mt_rand(0, substr_count($matches[1], '|'))];
}, $str, -1, $count);
}
return $str;
}
echo $sentence, PHP_EOL, sentence_spinning($sentence);