Search code examples
phpexplode

Dynamic explosion with specific character


I am trying to extract a string in php and convert them to comma separated strings

Here are some sample string I am working with and the results I need:

input :

 G1_C2_S3_T5  or  G4_C5_S4_T7_I6_H3

Result must be :

  G1,G1_C2,G1_C2_S3,G1_C2_S3_T5

  or

  G4,G4_C5,G4_C5_S4,G4_C5_S4_T7,G4_C5_S4_T7_I6,G4_C5_S4_T7_I6_H3

Input length can be dynamic for comma separation

Is this correct :

  $arr = explode("_", $string, 2);
  $first = $arr[0];

How can i do that in php?


Solution

  • Something like this should work, $string is the string you are working with

    //explode by underscore
    $parts = explode('_', $string);
    
    $c = [];
    //do until nothing else to pop from array
    while (!empty($parts)) {
        $c[] = implode('_', $parts);
       //will pop element from end of array
        array_pop($parts);
    }
    //reverse 
    $c = array_reverse($c);
    //glue it with comma
    echo implode(',', $c);