Search code examples
phpcombinationscpu-word

Get all 2-word combinations from a string of words


Here, i have the string....

$string = "Modern Country Kitchen";

I want split that string Word by Word wiht provision min 2 word, i want result like this...

$string1 = "Modern Country";
$string2 = "Country Kitchen";
$string3 = "Modern Kitchen";

How the logic code to make it be, what the php function should i used...?

So far my logic only be explode the string using explode() function..


Solution

  • So, let's start with a way to retrieve every combination/permutation of an array:

    function getAllCombinations(array $input)
    {
        if (count($input) > 0)
        {
            foreach (getAllCombinations(array_slice($input, 1)) as $combination)
            {
                foreach (array_keys($input) as $index) {
                    yield array_merge(
                        array_slice($combination, 0, $index),
                        [$input[0]],
                        array_slice($combination, $index)
                    );
                }
            }
        }
        else
        {
            yield $input;
        }
    }
    

    See it work here:

    php > foreach (getAllCombinations2([1, 2]) as $combination) {
    php { var_dump($combination);
    php { }
    array(2) {
      [0]=>
      int(1)
      [1]=>
      int(2)
    }
    array(2) {
      [0]=>
      int(2)
      [1]=>
      int(1)
    }
    php >
    

    Now we need to turn our input string into an array (you're right about explode()!):

    $string = "Modern Country Kitchen";
    $words = explode(" ", $string);
    

    Now it looks like this:

    php > var_dump($words);
    array(3) {
      [0]=>
      string(6) "Modern"
      [1]=>
      string(7) "Country"
      [2]=>
      string(7) "Kitchen"
    }
    

    So, now we can get an array of all combinations of these three words:

    $wordCombinations = iterator_to_array(getAllCombinations($words));
    

    Seen:

    php > var_dump(iterator_to_array(getAllCombinations2($words)));
    array(6) {
      [0]=>
      array(3) {
        [0]=>
        string(6) "Modern"
        [1]=>
        string(7) "Country"
        [2]=>
        string(7) "Kitchen"
      }
    
    ...
    

    Now, let's convert the combinations back into strings:

    $combinations = array_map(function ($words) {
        return implode(" ", $words);
    }, $wordCombinations);
    

    Now let's look at our end result:

    php > var_dump($combinations);
    array(6) {
      [0]=>
      string(22) "Modern Country Kitchen"
      [1]=>
      string(22) "Country Modern Kitchen"
      [2]=>
      string(22) "Country Kitchen Modern"
      [3]=>
      string(22) "Modern Kitchen Country"
      [4]=>
      string(22) "Kitchen Modern Country"
      [5]=>
      string(22) "Kitchen Country Modern"
    }
    php > var_dump($combinations[0]);
    string(22) "Modern Country Kitchen"