Answer the question
In order to leave comments, you need to log in
I am looking for a class function to iterate over all possible variants of a string
Good afternoon everyone.
I am looking for a class (function) in PHP to enumerate all possible variants of a string formed from such constructions {||}.
It will be absolutely great if the enumeration goes from the most unique string to the most non-unique one.
Answer the question
In order to leave comments, you need to log in
Recently, there was a topic on Habré. Didn't save the link, just the code:
<?
$str = "{Пожалуйста|Просто} сделайте так, чтобы это {удивительное|крутое|простое} тестовое предложение {изменялось {быстро|мгновенно} случайным образом|менялось каждый раз}";
$finishStrs = array();
getVariants($str);
function getVariants($str) {
global $finishStrs;
$strs = array();
if(preg_match("~\{([^{}]+)\}~siU", $str, $m)) {
$foundExpression = $m[1];
$currentVariants = explode("|", $foundExpression);
foreach($currentVariants as $var) {
$strs[] = str_replace('{'.$foundExpression.'}', $var, $str);
}
foreach($strs as $currentStr) {
if(preg_match("~\{([^{}]+)\}~siU", $currentStr, $m)) {
getVariants($currentStr);
} else {
$finishStrs[] = $currentStr;
}
}
} else {
$finishStrs = $str;
}
}
print_r($finishStrs);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question