dpge74512 2019-03-07 11:56
浏览 38
已采纳

在PHP中组合和混合字符串

I'm trying to loop something which can combine and mix 2 strings.

I want as a result, all possible combinations between characters of the given strings with the scheme "every character of the first string + every character of the second string". Example:

test & name
tame, teme, tese, tesme, teste, tname, tename, tesame, testme, tesname, testame
name & test
namt, nast, nest, namet, namst, ntest, namest, natest, namtest

I'm trying as following:

$str1 = "test";
$str2 = "name";

echo substr($str1,0,1).substr($str2,-3).','.substr($str1,0,2).substr($str2,-2).','.substr($str1,0,1).substr($str2,-4).','.substr($str1,0,3).substr($str2,-2)
.','.substr($str1,0,4).substr($str2,-1).','.substr($str1,0,2).substr($str2,-3).','.substr($str1,0,1).substr($str2,-5).','.substr($str1,0,2).substr($str2,-4)
.','.substr($str1,0,4).substr($str2,-2);

But this is partial and will require a lot to match all combinations. Also it's ugly. And also if the input strings are bigger or smaller, there will be a different amount of combinations.

Do you have any suggestion?

  • 写回答

2条回答 默认 最新

  • dourong4031 2019-03-07 13:08
    关注
    $str1 = "test";
    $str2 = "name";
    $len1 = strlen($str1);
    $len2 = strlen($str2);
    $arr3 =array();
    for ($i = 0; $i <=$len1; $i++) {  
        $arr3[] = substr($str1,0,$i+1).substr($str2,($i-$len1));
    }
    for ($i = 0; $i <=$len2; $i++) {  
        $arr3[] = substr($str2,0,$i+1).substr($str1,($i-$len2));
    }
    
    $arr3 = array_unique($arr3);
    echo implode(',', $arr3);
    

    I came up with this

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里