Splitting out all phrases in a string of words

Hi all,

I'm looking for some efficient php code to do the following:

Consider an input string of "one two three four" (any numer of words delimited by spaces).

I would like to output all possible combinations of phrases and words in that sentance e.g. :

one two three four
one two three
one two
two three four
three four

Would like to then put them in a string comma seperated (e.g. one two three four, one two three, one two, one, two three four,...)

Doesn't have to be in that order but any help on this much appreciated - driving me mad!

Who is Participating?
DerokorianConnect With a Mentor Commented:
Wrote this, output what you were hoping for, added the vardump at the bottom to show what it looks like before imploding.

$test = "one two three four";
$rescount = 1;
$results = array();
$result[] = $test;

$words = explode(' ',$test);
$wordc = count($words);

for( $i=0; $i<$wordc; $i++ ) {
	for( $j=$wordc; $j>0; $j-- ) {
		$results[$rescount] = '';
		for( $k=$i; $k<$j; $k++ ) {
			$results[$rescount] .= ' '. $words[$k];
		if( !empty($results[$rescount]) ) $rescount++;
if( empty($results[$rescount]) ) unset($results[$rescount]);

echo implode(',',$results);

echo '<pre>';
echo '</pre>';

Open in new window

Ray PaseurCommented:
What would you want for the output from this:

one two two three

Thanks, ~Ray
dolythgoeAuthor Commented:
That's just brilliant - thanks so much :)
Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

dolythgoeAuthor Commented:
I've requested that this question be closed as follows:

Accepted answer: 0 points for dolythgoe's comment http:/Q_27302373.html#36519810

for the following reason:

Top reply in no time at all
If the reply works, please accept it as the solution, not your own comment as that does not award points.
dolythgoeAuthor Commented:
Opps trying to accept my own question!
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.