Questions about character string combinations

Source: Internet
Author: User
Note the problem of character string combination by experts (where the number of # and $ is not fixed, that is, the number of layers is not fixed, and it cannot be done with a fixed loop). The original string is as follows: a $ B $ c # A $ B $ C #1 $2 $3 need to combine N strings & nbsp; and use commas to connect aA1, aA2, aA3, aB1, aB2, aB3, aC1, aC2, and aC
Note (where the number of "#" and "$" is not fixed, that is, the number of layers is not fixed)

The original string is as follows:
A $ B $ c # A $ B $ C #1 $2 $3
Requires that N strings be combined and connected with commas
AA1, aA2, aA3, aB1, aB2, aB3, aC1, aC2, aC3, bA1, bA2, bA3, bB1, bB2, bB3, bC1, and so on.

Provide several strings:
A $ B $ c # A $ B $ C #1 $2 $3 # y $ u
A $ B $ c # A $ B $ C $ D $ E $ F #1 $2 $3 # y $ u #0 $9 $8 $7 $6 $5
The string is not fixed and there is no regularity.


------ Solution --------------------
$s = 'a$b$c#A$B$C#1$2$3';

foreach(explode('#', $s) as $v) {
  $t[] = explode('$', $v);
}

echo join(',', foo($t));

function foo($ar) {
  $t = array_shift($ar);
  if(count($ar) > 1) {
    $r = foo($ar);
  }else $r = current($ar);
  foreach($t as $t1) {
    foreach($r as $r1) {
      $res[] = $t1.$r1;
    }
  }
  return $res;
}


AA1, aA2, aA3, aB1, aB2, aB3, aC1, aC2, aC3, bA1, bA2, bA3, bB1, bB2, bB3, bC1, bC2, bC3, A1, CA 2, a3, cB1, cB2, cB3, cC2, cC3

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.