Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 340
  • Last Modified:

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
one
two three four
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!

Cheers
David
0
dolythgoe
Asked:
dolythgoe
  • 3
  • 2
1 Solution
 
DerokorianCommented:
Wrote this, output what you were hoping for, added the vardump at the bottom to show what it looks like before imploding.
<?php

$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>';
var_dump($results);
echo '</pre>';

Open in new window


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

one two two three


Thanks, ~Ray
0
 
dolythgoeAuthor Commented:
That's just brilliant - thanks so much :)
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
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
0
 
DerokorianCommented:
If the reply works, please accept it as the solution, not your own comment as that does not award points.
0
 
dolythgoeAuthor Commented:
Opps trying to accept my own question!
0

Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now