Search code examples
phpalgorithmstringfactorial

progressive word combination of a string


I need to obtain a progressive word combination of a string.

E.g. "this is string" Output: "this is string" "this is" "this string" "is string" "this" "is" "string"

Do you know similar algorithm? (I need it in php language) Thanks ;)


Solution

  • This is a simple code solution to your problem. I concatenate each string recoursively to the remaining ones in the array.

    $string = "this is a string";  
    $strings = explode(' ', $string);
    
    // print result
    print_r(concat($strings, ""));
    
    // delivers result as array
    function concat(array $array, $base_string) {
    
        $results = array();
        $count = count($array);
        $b = 0;
        foreach ($array as $key => $elem){
            $new_string = $base_string . " " . $elem;
            $results[] = $new_string;
            $new_array = $array;
    
            unset($new_array[$key]);
    
            $results = array_merge($results, concat ($new_array, $new_string));
    
        }
        return $results;
    }