<?php | |
/** | |
* | |
* @param string $txt Text to variate. All synonyms myst be placed in curly parenthesis, separated by pipe sign | |
* (ex. $txt = "I own {2|3} phones manufactured by {Apple|Samsung|HTC}.") | |
* @param boolean $shuffle Shuffle variations. If false, | |
* @return string[] All possible variations of $txt | |
*/ | |
function create_text_variations($txt, $shuffle = true) { | |
$pattern = "/\{([^\}]+)\}/u"; | |
$matches = null; | |
preg_match_all($pattern, $txt, $matches); | |
$max_arr = array_map(function($curr){ return count(explode('|', $curr)); }, $matches[1]); | |
$variations = []; | |
// Find how many variations we expect | |
$max = array_product($max_arr); | |
$segments = count($max_arr); | |
$curr_arr = array_fill(0, $segments, 0); | |
$curr_segment = 0; | |
while (count($variations) < $max) { | |
$variations[] = preg_replace_callback($pattern, function($match) use($max_arr, $segments, &$curr_arr, &$curr_segment) { | |
$possible = explode('|', $match[1]); | |
$return = $possible[$curr_arr[$curr_segment]]; | |
$curr_segment++; | |
if ($curr_segment == $segments) { | |
$curr_segment = 0; | |
$i = 0; | |
$j = 0; | |
$incremented = false; | |
while (!$incremented && $i < $segments) { | |
if ($curr_arr[$i]+1 < $max_arr[$i]) { | |
$curr_arr[$i]++; | |
$incremented = true; | |
while ($j < $i) { | |
$curr_arr[$j++] = 0; | |
} | |
break; | |
} else { | |
$i++; | |
} | |
} | |
} | |
return $return; | |
}, $txt); | |
} | |
if ($shuffle) { | |
shuffle($variations); | |
} | |
return $variations; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment