04 Aug
Posted by: admin in: PHP Solutions
Sometimes you need to change the word order in a line for some reason. I am going to show you a PHP solution that allows you to create all possible word combinations from a string. The code below should explain you all operations that are performed.
<?
// Factorial
function fact($s){
if ($s==0) return 1;
else return $fact = $s * fact($s-1);
}$phrase=”Your Phrase Comes Here”;
// Let’s count the number of words by creating an array
$words=explode(” “, $phrase);
$n=count($words);// Here comes a loop that creates all possible combinations of array positions
for ($m=1; $m<=fact($n); $m++)
{
$ken = $m-1;
$f = 1;
$a = array();
for($iaz=1; $iaz<=$n; $iaz++)
{
$a[$iaz] = $iaz;
$f = $f*$iaz;
}
for($iaz=1; $iaz<=$n-1; $iaz++)
{
$f = $f/($n+1-$iaz);
$selnum = $iaz+$ken/$f;
$temp = $a[$selnum];
for($jin=$selnum; $jin>=$iaz+1; $jin–)
{
$a[$jin] = $a[$jin-1];
}
$a[$iaz] = $temp;
$ken = $ken%$f;
}
$t=1;// Let’s start creating a word combination: we have all the necessary positions
$newphrase=”";// Here is the while loop that creates the word combination
while ($t<=$n)
{
$newphrase.=$words[$a[$t]-1].” “;
$t++;
}
// Output of the phrase
echo $newphrase.”\r\n”;}
?>
The example above will output:
Your Phrase Comes Here
Your Phrase Here Comes
Your Comes Phrase Here
Your Comes Here Phrase
Your Here Phrase Comes
Your Here Comes Phrase
Phrase Your Comes Here
Phrase Your Here Comes
Phrase Comes Your Here
Phrase Comes Here Your
Phrase Here Your Comes
Phrase Here Comes Your
Comes Your Phrase Here
Comes Your Here Phrase
Comes Phrase Your Here
Comes Phrase Here Your
Comes Here Your Phrase
Comes Here Phrase Your
Here Your Phrase Comes
Here Your Comes Phrase
Here Phrase Your Comes
Here Phrase Comes Your
Here Comes Your Phrase
Here Comes Phrase Your
You can play with number combinations instead of words.
Tags: all array combinations, all possible combinations of an array php, all possible word combinations, create all word combinations, create word combinations PHP, for generate all array combinations, generate all combination from array, Invert a string PHP, inverting a php string, php generate combinations, php invert words, php output all combinations, PHP script number combination, word combinations
Leave a reply