R
R
Rekrut2011-01-16 15:53:53
PHP
Rekrut, 2011-01-16 15:53:53

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

2 answer(s)
T
torchello, 2011-01-16
@torchello

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);

C
Cord, 2011-02-10
@Cord

for those who suddenly came here, having googled my task in a vacancy - this algorithm does not take into account the positional nature of the entry and is not correct in the general case (and not for a particular line).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question