Php 通过更改大小写排列字符串(不影响数字)
我试图从给定的字符串中获得可能的大小写组合,而不影响字符串中的数字。我目前发现这段代码在序列中输入一个数字之前一直有效。以下是我目前正在使用的代码:Php 通过更改大小写排列字符串(不影响数字),php,permute,Php,Permute,我试图从给定的字符串中获得可能的大小写组合,而不影响字符串中的数字。我目前发现这段代码在序列中输入一个数字之前一直有效。以下是我目前正在使用的代码: <?php if (isset($_GET['word'])) { $word = $_GET["word"]; function permute($input){ $n = strlen($input); $max = 1 << $n;
<?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 abc1 abc1 abc1 abc1 abc1 abc1 abc1 abc1 abc1 abc1 abc1 abc1这里有一个使用递归函数的选项,将第一个字符的排列与字符串其余部分的所有可能排列组合在一起:
/**
* @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);