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?
source share