phpregexplaceholderdelimitedcapture-group

Capture an indeterminant number of delimited values inside of a square braced placeholder in a string


I have the following regex:

\[([^ -\]]+)( - ([^ -\]]+))+\]

This match the following successfully:

[abc - def - ghi - jkl]

BUT the match is:

Array
(
    [0] => [abc - def - ghi - jkl]
    [1] => abc
    [2] =>  - jkl
    [3] => jkl
)

What I need is something like this:

Array
(
    [0] => [abc - def - ghi - jkl]
    [1] => abc
    [2] =>  - def
    [3] => def
    [4] =>  - ghi
    [5] => ghi
    [6] =>  - jkl
    [7] => jkl
)

I'm able to do that in C# looking at the groups "captures". How can I do that in PHP?


Solution

  • This is not the job for the regexp. Match against \[([^\]]*)\], then explode the first capture by the " - ".

    <?php                                                                       
      $str = "[abc - def - ghi - jkl]";
      preg_match('/\[([^\]]*)\]/', $str, $re);
      $strs = explode(' - ', $re[1]);
      print_r($strs);
    ?>