Last active
May 5, 2019 17:25
-
-
Save MightyPork/0f78fd72a2acb14c8ecb90a2492205c2 to your computer and use it in GitHub Desktop.
PHP function to expand strings array using {a,b,c} and {1..5}
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| function expandBashRepeat($sourceStrings) | |
| { | |
| if (is_string($sourceStrings)) $sourceStrings = [$sourceStrings]; | |
| $outputs = []; | |
| foreach($sourceStrings as $str) { | |
| $i=0; | |
| $arrays = []; | |
| $str2 = preg_replace_callback('/\{([^{}]+)\}/', function($m) use(&$i, &$arrays) { | |
| $seq = explode(',',$m[1]); | |
| if(count($seq)>=2) { | |
| $arrays[$i] = $seq; | |
| } else { | |
| $ab = explode('..',$m[1]); | |
| if (!$ab) { $outputs[] = $str; return $m[0]; } | |
| $a = intval($ab[0]); | |
| $b = intval($ab[1]); | |
| $arrays[$i] = range($a, $b); | |
| } | |
| return '{{'.($i++).'}}'; | |
| }, $str); | |
| $strs = [$str2]; | |
| $tmpstrs = []; | |
| for($n=count($arrays)-1;$n>=0;$n--) { | |
| $arr = $arrays[$n]; | |
| $tmpstrs = []; | |
| foreach($arr as $subs) { | |
| foreach($strs as $ss) { | |
| $tmpstrs[] = str_replace('{{'.$n.'}}', $subs, $ss); | |
| } | |
| } | |
| $strs = $tmpstrs; | |
| } | |
| $outputs = array_merge($outputs, $strs); | |
| } | |
| return $outputs; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment