PHP - 字符串的所有组合大小写字符

标签 php combinations uppercase lowercase

我尝试获取字符串的所有大小写字符组合。例如我的字符串是abc。我需要得到这样的结果,字符串 3 个字符的所有组合:(2^0) x (2^1) x (2^2) = 8:

abc
Abc
ABc
ABC
aBC
abC
AbC
aBc

我的代码是这样的,但我有一个问题,我的代码有重复的情况并且不返回 AbCaBc:

<?php
function opposite_case($str) 
{ 
    if(ctype_upper($str)) 
    { 
        return strtolower($str); 
    } 
    else 
    { 
        return strtoupper($str); 
    } 
} 

$str = "abc";

for($i = 0 ; $i < strlen($str) ; $i++)
{
    for($j = 0 ; $j < strlen($str) ; $j++) 
    {
        $str[$j] = opposite_case($str[$j]);
        echo $str."<br>"; 
    }
}
?>

最佳答案

一些代码转储,其中包含一些注释以备不时之需。这是从 Java 实现转换而来的 - https://stackoverflow.com/a/6785649/296555

http://sandbox.onlinephpfunctions.com/code/aadefa26561a0e33c48fd1d147434db715c8fc59

2020 年 11 月 - 此答案已更新 2 个地方。有关详细信息,请参阅修订历史。

<?php

function calculatePermutations($text) {

    $permutations = array();
    $chars = str_split($text);
    
    // Count the number of possible permutations and loop over each group 
    for ($i = 0; $i < 2 ** strlen($text); $i++) {
        
        // Loop over each letter [a,b,c] for each group and switch its case
        for ($j = 0; $j < strlen($text); $j++) {
            
            // isBitSet checks to see if this letter in this group has been checked before
            // read more about it here: http://php.net/manual/en/language.operators.bitwise.php
            $permutations[$i][] = (isBitSet($i, $j)) 
                ? strtoupper($chars[$j]) 
                : $chars[$j];
        }
    }
    
    return $permutations;
}

function isBitSet($n, $offset) {
  return ($n >> $offset & 1) != 0;
}

print_r(calculatePermutations('abc'));

关于PHP - 字符串的所有组合大小写字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44724631/

相关文章:

mysql - 如何在 MySQL 表中查找所有大写字符串?

javascript - 确定字符串中第一个字母的大小写(大写/小写)

javascript - 如何从 JavaScript 或 PHP 中的字符串中删除 '।'?

javascript - 如何从动态按钮获取 id? (jQuery)

C 中的组合求和

给定一个数字的Javascript我想要所有可能的组合和元素数组

php - 路由模型绑定(bind)不适用于 laravel 中的路由组

php - Laravel Sanctum 身份验证 :sanctum middleware with Angular SPA unauthenticated response

c++ - 基于初始输入生成所有组合(n 选择 k)的快速算法

c - C语言中的大写