php可用选项[重复]

Possible Duplicate:
How to generate all permutations of a string in PHP?

I want to make a script in php that will take this input:

12a

And output a result like so:

1, 2, a, 12, 1a, 21, 2a, a1, a2, 12a, 1a2, 21a, 2a1.

I did some research but I cannot find any script that will do this.

Here is a modified function from this answer

function permute($str,$i,$n) {
   if ($i == $n)
       print "$str
";
   else {
        for ($j = $i; $j < $n; $j++) {
          swap($str,$i,$j);
          permute($str, $i+1, $n);
          swap($str,$i,$j); // backtrack.
       }
   }
}

// function to swap the char at pos $i and $j of $str.
function swap(&$str,$i,$j) {
    $temp = $str[$i];
    $str[$i] = $str[$j];
    $str[$j] = $temp;
}   

$str = "12a";
$len = strlen($str);
for($i =0; $i <= $len; $i++) {
   permute($str,0,$i + 1); // call the function.
}

This is not perfect, because your output set is not well-defined. First, figure out what your output set should look like, then use below as a way to get started.

<?php

$input = "12a";
$input_array = str_split($input, 1);//get an array of each individual character

$max_length = strlen($input);
$length = 01;
$result = array();

foreach($input_array as $character) {
  $result[] = $character;
}

while ($length < $max_length){
  foreach($result as $substring) {
    foreach($input_array as $character) {
      $result[] = $substring.$character;
    }
  }
  $length++;
}

foreach ($result as $result_string) {
  echo $result_string.", ";
}

As a note, in general these sorts of algorithms make use of 'dynamic programming'.