4

I want to build an array in php that contains every possible capitalization permutation of a word. so it would be (pseudocode)

function permutate($word){
  for ($i=0; $i<count($word); $i++){
    ...confused here...
    array_push($myArray, $newWord)   
  }
  return $myArray;
}

So say I put in "School" I should get an array back of

{school, School, sChool, SCHool, schOOl, ... SCHOOL}

I know of functions that capitalize the string or the first character, but I am really struggling with how to accomplish this.

  • 3
    This is the effectively problem as generating all 2^n binary strings of length `n = strlen($word)`. – Paul Apr 27 '13 at 04:24
  • 1
    Out of interest, why do you need to do this? If you're looking for a case insensitive match, just convert to lower case beforehand (or use `strcasecmp()`)... – John Carter Apr 27 '13 at 04:27
  • Check out http://stackoverflow.com/questions/905317/permutations-of-capitalization This same question was for c#, not php, but it should help in thinking through the problem. – Sean Apr 27 '13 at 04:30
  • I wish that I could. However, I don't control what a particular mobile app sends me and I need to check all permutations to see if it matches anything that I have stored in the DB. The value is hashed, so I will end up hashing all permutations in the end and comparing all hashes to the one sent. Hopefully my reasoning makes sense. – user2325935 Apr 27 '13 at 04:30
  • 5
    @user2325935: This seems like a horrible solution to whatever problem you're trying to solve. If I put in `permute('super long word that you never expected')`, your server will be working for a while. – Blender Apr 27 '13 at 04:32

1 Answers1

9

This should do it for you:

function permute($word){
    if(!$word)
        return array($word);
    $permutations = array();
    foreach(permute(substr($word, 1)) as $permutation){
        $lower = strtolower($word[0]);
        $permutations[] = $lower . $permutation;

        $upper = strtoupper($word[0]);
        if($upper !== $lower)
            $permutations[] = $upper . $permutation;
    }
    return $permutations;
}

Codepad Demo

However, for your particular use case there may be a better solution. As there are 2^n permutations for a string of length n. It will be infeasible to run this (or even to generate all those strings using any method at all) on a much longer string.

In reality you should probably be converting strings to one particular case before hashing them, before storing them in the database, if you want to do case-insensitive matching.

Paul
  • 139,544
  • 27
  • 275
  • 264