Suppose I have a string, like so:
$string = 'president barack obama';
Now, suppose I want to explode this into an array, breaking at the words. You'd think I can just use explode()
, right? That works, but what if I want an array of all possible left-to-right combinations of the words? Like so:
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?
I've come up with one possible solution so far, but I'm hoping one of you can give me a better idea. I imagine approaching this like so:
$current_word . ' ' . $new_word;
. Do this for each word.Now, that will probably work. However, it seems annoying, and I'm afraid someone else may have a better way of doing this. What do you all recommend? Is there, perhaps, a PHP function that does just this that I don't know about?
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'
)
*/
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
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With