1

I have text like this between brackets [ and ]:

$commands = "[CMD1,[CMD2],[CMD3,[CMD4],[CMD5]]]";

and execute with this PHP function:

preg_match_all('/\\[(.*?)\\]/', $commands, $matches);

And output of index 1 is:

array(2) (
    ...
    1 => array(3) (
        0 => string(10) "CMD1,[CMD2"
        1 => string(10) "CMD3,[CMD4"
        2 => string(4) "CMD5"
    )
)

however I want to process the deepest one first, output like this:

array(2) (
    ...
    1 => array(3) (
        0 => string(4) "CMD5"
        1 => string(4) "CMD4"
        2 => string(4) "CMD3"
        3 => string(4) "CMD2"
        4 => string(4) "CMD1"
    )
)

Can preg_match_all do that?

Tomero Indonesia
  • 1,685
  • 2
  • 16
  • 17

2 Answers2

1

You can use this below code.

$commands = "[CMD1,[CMD2],[CMD3,[CMD7],[CMD4],[CMD5]]]";
$array = explode(",", $commands);

array_walk($array, function(&$val, $key){
     $val = trim( trim($val,"]") ,"[");
});

rsort($array);

print_r($array);

Output will be:

Array
(
    [0] => CMD7
    [1] => CMD5
    [2] => CMD4
    [3] => CMD3
    [4] => CMD2
    [5] => CMD1
)
shiyani suresh
  • 778
  • 12
  • 12
1

You can use

preg_match_all('/[^][,]+/', $commands, $matches)

See the regex demo. The [^][,]+ regex matches one or more occurrences of any char other than ], [ and ,.

Since the regex engine processes the string (i.e. searched for pattern matches) from left to right, you cannot get the matches in the order you specified in the question. If you want to reverse them, use rsort.

See this PHP demo:

$commands = "[CMD1,[CMD2],[CMD3,[CMD4],[CMD5]]]";
if (preg_match_all('/[^][,]+/', $commands, $matches)) {
    $array = $matches[0];
    rsort($array);
    print_r($array);
}
// => Array( [0] => CMD5 [1] => CMD4  [2] => CMD3 [3] => CMD2 [4] => CMD1 )
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563