UPDATE: Let me rephrase my question:
Take a string: (x)ello (y)orld
I want to find all possible combinations where i put in the letters w,z and c in place of (x) and (y) using PHP. My approach below was clearly wrong...
OLD QUESTION
I'm working on a PHP-function to find all possible combinations of a string replacing certain characters with a list of characters.
Say the string is "Hello World" and I want to find all possible combinations where I replace H and W with P and K and S so the result will be:
- Hello World
- Pello World
- Pello Porld
- Pello Korld
- Hello Korld
- Hello World
- Kello Porld
- Sello Porld
- Sello Sorld
- Hello Sorld
- ...
and so on. The list should contain all possible combinations.
This is what i got so far:
/**
* Get all permuations of a string based on an array of translations
*
* @author Kovik :) http://koviko.net/
* @param string $str
* @param array $rules
* @return array
*/
function get_all_permutations($str, array $rules) {
$rules_power_set = array(array());
foreach ($rules as $from => $to) {
foreach ($rules_power_set as $current_set) {
$rules_power_set[] = array_merge(array($from => $to), $current_set);
}
}
$permutations = array();
foreach ($rules_power_set as $rules) {
$permutations[] = strtr($str, $rules);
}
return $permutations;
}
$rules = array(
'H' => 'S',
'H' => 'K',
'H' => 'P',
'W' => 'S',
'W' => 'K',
'W' => 'P'
);
$input = "Hello World";
$permutations = get_all_permutations($input, $rules);
print_r($permutations);
Result:
Array
(
[0] => Hello World
[1] => Pello World
[2] => Hello Porld
[3] => Pello Porld
)
I hope it makes sense and someone has cracked this nut :-)
replace H and WwithP and K and Swith any occurrences$rulesarray is wrong at final state it contains just 2 elements instead of 6, because array keys must be unique