更新: 让我重新表述一下我的问题:
取一个字符串:(x)ello (y)orld
我想找到所有可能的组合,其中我使用 PHP 输入字母 w、z 和 c 来代替 (x) 和 (y)。我的下面的方法显然是错误的......
老问题
我正在开发一个 PHP 函数来查找用字符列表替换某些字符的字符串的所有可能组合。
假设字符串是“Hello World”,我想找到所有可能的组合,其中我将 H 和 W 替换为 P、K 和 S,结果将是:
- Hello World
- 佩洛世界
- 佩洛波尔德
- 佩洛·科尔德
- 你好科尔德
- Hello World
- 凯洛·波尔德
- 塞洛波尔德
- Sello Sorld
- 你好, Solr 德
- ...
等等。该列表应包含所有可能的组合。
这是我到目前为止得到的:
/**
* 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);
结果:
Array
(
[0] => Hello World
[1] => Pello World
[2] => Hello Porld
[3] => Pello Porld
)
我希望这是有道理的,并且有人已经解决了这个问题:-)
最佳答案
我不认为这个问题是重复的,无论如何我无法从链接中得到正确的答案。
这是解决方案(我稍后会解释它是如何工作的):
/**
* finds the indexes of characters for replacement letter
*
* @param string $table
* @param array|string $freeSits array of
* letter or string `A|f|p...` can be passed
* @param bool $caseSensitive
* @return array
*/
function getSeatNumbers($table, $freeSits, $caseSensitive = false)
{
if (is_array($freeSits))
{
$freeSits= implode('|', $freeSits);
}
$flag = $caseSensitive ? '' : 'i' ;
preg_match_all("/$freeSits/$flag", $table, $match, PREG_OFFSET_CAPTURE);
$positions = array();
foreach ($match[0] as $i)
{
$positions[] = $i[1];
}
return $positions;
}
/**
* do the sitting
* @param string $table
* @param array $seats
* @param array $guests
* @param array $variations
*/
function recursiveSitting($table, array $seats, array $guests, &$variations)
{
$s = $seats;
while (count($s))
:
$seat = current($s);
$s = array_slice($s, 1);
$t = $table;
foreach ($guests as $guest)
{
$t[$seat] = $guest;
if(count($s) > 0)
{
recursiveSitting($t, $s, $guests, $variations);
}
$variations[] = $t;
}
endwhile;
}
$table = "Hello World";
$freeSits= array('H','W','D');
$guests = array('P','K','S');
$seats = getSeatNumbers($table, $freeSits, true);
$variations = array($table);
recursiveSitting($table, $seats, $guests, $variations);
echo "<pre>";
//you can sort the array
sort($variations);
print_r($variations);
关于php - 使用外部字母数组对 PHP 中的字符串进行排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25324068/