function str_replace_count($search, $replace, $subject, $times) {
$subject_original = $subject;
$len = strlen($search);
$pos = 0;
for ($i = 1; $i <= $times; $i++) {
$pos = strpos($subject, $search, $pos);
if ($pos !== false) {
$subject = substr($subject_original, 0, $pos);
$subject.=$replace;
$subject.=substr($subject_original, $pos + $len);
$subject_original = $subject;
} else {
break;
}
}
return $subject;
}
function spinTextAll($spintax) {
$results[] = $spintax;
while (preg_match('/{([^{}]+)}/', $spintax, $matches)) { //find a match
$parts = explode('|', $matches[1]); //break up all the possible values
$spintax = str_replace_count($matches[0], $parts[mt_rand(0, count($parts) - 1)], $spintax, 1); //randomly replace it in the master string so that we don't keep matching the same element
foreach ($parts as $part) { // loop through possible values
foreach ($results as $result) { //loop through our strings we are building
if (strstr($result, $matches[0])) { //only if there is a matching element do a replace
$results[] = str_replace_count($matches[0], $part, $result, 1); // replace in the strings we are building
}
}
}
}
$i = 0;
foreach ($results as $result) { //loop though our results
if (!preg_match('/{([^{}]+)}/', $result, $matches)) { //only count values that are complete
$i++;
echo $i . ' ' . $result . '<br />';
}
}
}
$spintax = 'this {is|mightbe} some {sort|kind} {of|if} {syntax|code}';
spinTextAll($spintax);