-1

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?

Script47
  • 14,230
  • 4
  • 45
  • 66
Dreg Korig
  • 165
  • 2
  • 10

2 Answers2

0

You can try like this

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

$len1 = strlen($str1);
$len2 = strlen($str2);

for($i=0; $i<$len1; $i++)
{
  for($j=$i+1; $j<=$len1; $j++)
  {
    for($k=0; $k<$len2; $k++)
    {
      for($m=$k+1; $m<=$len2; $m++)
      {
        echo substr($str1, $i, $j - $i).substr($str2, $k, $m - $k)."\n";
      }
    }
  }
}
IVO GELOV
  • 13,496
  • 1
  • 17
  • 26
  • almost ok, but the order of the characters inside a word should not be shuffled. – Dreg Korig Mar 07 '19 at 13:38
  • 1
    @DregKorig Would you be so kind to define the rules for this algorithm ? I assume you already know the rules and only struggle to implement them in code, right ? You are not asking us to translate your imprecise/vague explanation into an algorithm, right ? – IVO GELOV Mar 07 '19 at 13:48
0
$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

Shoyeb Sheikh
  • 2,659
  • 2
  • 10
  • 19