$state) { if($state == 'open') { $depth++; $history[] = $position; } else { $lastPosition = end($history); $lastKey = key($history); unset($history[$lastKey]); $store[$depth][] = mb_substr($string, $lastPosition + $openingConstructLength, $position - $lastPosition - $closingConstructLength); $depth--; } } krsort($store); # Remove the old array and make sure we know what the original state of the top level spin blocks was unset($order); $original = $store[1]; # Move through all elements and spin them foreach($store as $depth => $values) { foreach($values as $key => $spin) { # Get the choices $choices = explode('|', $store[$depth][$key]); $replace = $choices[mt_rand(0, count($choices) - 1)]; # Move down to the lower levels $level = $depth; while($level > 0) { foreach($store[$level] as $k => $v) { $find = $openingConstruct.$store[$depth][$key].$closingConstruct; if($level == 1 AND $depth == 1) { $find = $store[$depth][$key]; } $store[$level][$k] = str_replace_first($find, $replace, $store[$level][$k]); } $level--; } } } # Put the very lowest level back into the original string foreach($original as $key => $value) { $string = str_replace_first($openingConstruct.$value.$closingConstruct, $store[1][$key], $string); } return $string; } # Similar to str_replace, but only replaces the first instance of the needle function str_replace_first($find, $replace, $string) { # Ensure we are dealing with arrays if(!is_array($find)) { $find = array($find); } if(!is_array($replace)) { $replace = array($replace); } foreach($find as $key => $value) { if(($pos = strpos($string, $value)) !== false) { # If we have no replacement make it empty if(!isset($replace[$key])) { $replace[$key] = ''; } $string = mb_substr($string, 0, $pos).$replace[$key].mb_substr($string, $pos + mb_strlen($value)); } } return $string; } # Finds all instances of a needle in the haystack and returns the array function strpos_all($haystack, $needle) { $offset = 0; $i = 0; $return = false; while(is_integer($i)) { $i = strpos($haystack, $needle, $offset); if(is_integer($i)) { $return[] = $i; $offset = $i + mb_strlen($needle); } } return $return; } function spinner($text) { $txt = preg_split("/{|}/", $text); foreach($txt as $key => $t){ if($key%2){ $spin = preg_split("/\|/", $t); $txt[$key] = $spin [mt_rand(1,count($spin)-1)]; } } $string = implode("", $txt); return $string; } echo spin($_POST['content']); } ?>