Blow up all possible combinations from left to right?

Suppose I have a line, for example:

$string = 'president barack obama'; 

Now suppose I want to blow this into an array, breaking words. You think I can just use explode() , right? This works, but what if I want an array of all possible word combinations from left to right? For instance:

 Array ( [0] => 'barack' [1] => 'barack obama' [2] => 'obama' [3] => 'president' [4] => 'president barack' [5] => 'president barack obama' ) 

What is the most efficient way to do this?


Possible Solution:

I have one possible solution, but I hope one of you can give me a better idea. I assume this is so:

  • Search normally.
  • Scroll through each word.
  • For each word, store it in an array. Then check if there is another word in the array (after itself). If there is, add a new array value that consists of $current_word . ' ' . $new_word; $current_word . ' ' . $new_word; . Do it for every word.

Now it will probably work. However, this seems annoying, and I'm afraid someone might have a better way to do this. What do you all recommend? Is there perhaps a PHP function that does exactly this that I don't know about?

+4
source share
2 answers

This should do what you are looking for:

 $string = 'president barack obama won'; $results = getWordPermutaions($string); print_r($results); function getWordPermutaions($inStr) { $outArr = Array(); $tokenArr = explode(" ", $inStr); $pointer = 0; for ($i=0; $i<count($tokenArr); $i++) { $outArr[$pointer] = $tokenArr[$i]; $tokenString = $tokenArr[$i]; $pointer++; for ($j=$i+1; $j<count($tokenArr); $j++) { $tokenString .= " " . $tokenArr[$j]; $outArr[$pointer] = $tokenString; $pointer++; } } return $outArr; } /* $results: Array ( [0] => 'president' [1] => 'president barack' [2] => 'president barack obama' [3] => 'president barack obama won' [4] => 'barack' [5] => 'barack obama' [6] => 'barack obama won' [7] => 'obama' [8] => 'obama won' [9] => 'won' ) */ 
+5
source

Another working solution:

  $s = 'president barack obama won'; function myExplode($s) { $ex = explode(" ", $s); $ec = 0; $x = 0; foreach ($ex as $word) { $rs = isset($res) ? sizeof($res) : 0; if ($rs > 0) for ($i=$ec-$x; $i < $rs; $i++) $res[] = "{$res[$i]} {$word}"; $x++; $res[] = $word; $ec = sizeof($res); } return isset($res) ? $res : false; } print_r( myExplode($s) ); 

Output

 Array ( [0] => president [1] => president barack [2] => barack [3] => president barack obama [4] => barack obama [5] => obama [6] => president barack obama won [7] => barack obama won [8] => obama won [9] => won ) 
+3
source

All Articles