1

我试图从给定的字符串中获取可能的大写和小写组合,而不影响字符串中的数字。我目前发现这段代码一直有效,直到您将数字放入序列中。这是我现在正在使用的代码:

<?php
if (isset($_GET['word'])) {

    $word = $_GET["word"];

    function permute($input){ 
        $n = strlen($input); 
        
        $max = 1 << $n; 

        $input = strtolower($input); 
        
        for($i = 0; $i < $max; $i++) 
        { 
            $combination = $input; 
            
            for($j = 0; $j < $n; $j++) 
            { 
                if((($i >> $j) & 1) == 1) 
                    $combination[$j] = chr(ord($combination[$j]) - 32); 
            } 
            
            echo $combination . " "; 
        } 
    } 
  
permute($word); 
}
?>

“abc1”的示例输出

在此处输入图像描述

我怎样才能得到输出只是:

abc1 abc1 abc1 abc1 abC1 abc1 abc1 abc1

4

1 回答 1

1

这是一个使用递归函数的选项,将第一个字符的排列与字符串其余部分的所有可能排列组合起来:

/**
 * @param string $str
 * @return string[]
 */
function findAllPermutations(string $str): array
{
  if ($str === '') {
    return [];
  }
  if (strlen($str) === 1) {
    return ctype_digit($str) ? [$str] : [strtolower($str), strtoupper($str)];
  }

  $permutations = [];
  foreach (findAllPermutations($str[0]) as $firstCharPermutation) {
    foreach (findAllPermutations(substr($str, 1)) as $restPermutation) {
      $permutations[] = $firstCharPermutation . $restPermutation;
    }
  }

  return $permutations;
}

用法:

$permutations = findAllPermutations('abc1');
print_r($permutations);
// or, if you want them separated with a space:
echo implode(' ', $permutations);

演示

于 2020-07-26T20:12:13.290 回答