Search code examples
phparraysregexmultidimensional-arraypreg-match-all

PHP Split String contains arrays inside bracket into Multidimensional Arrays


I have a string where there are arrays separated by {|} like this :

$string = "Hi, {Mr.|Mrs.} {Alvin|Dale}! Good Morning!";

One of the many things I've tried :

$string = "Hi, {Mr.|Mrs.} {Alvin|Dale}! Good Morning!";
preg_match_all("/[()=]|\\{[^\}]+\\}|[+-]|[^=]+$/", $string, $matches);

Expected result:

$result = array ( 
0 => array ( 0 => 'Hi, '), 
1 => array ( 0 => 'Mr.', 1 => 'Mrs.'),
2 => array ( 0 => ' '), 
3 => array ( 0 => 'Alvin', 1 => 'Dale'), 
4 => array ( 0 => '! Good Morning!')
);

Actual result:

$result = array ( 
0 => 'Hi, {Mr.|Mrs.} {Alvin|Dale}! Good Morning!'
);

Solution

  • You could split the string on matching from an opening curly till a closing curly brace, and keep the values you split on using that pattern in a capture group for the inner part of the curly braces

    Then you can use array_map and split on |.

    For example

    $pattern = "/{([^{}]+)}/";
    $string = "Hi, {Mr.|Mrs.} {Alvin|Dale}! Good Morning!";
    $result = preg_split($pattern, $string, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
    
    $result = array_map(function($x) {
        return explode('|', $x);
    }, $result);
    

    Output

    array (
      0 => 
      array (
        0 => 'Hi, ',
      ),
      1 => 
      array (
        0 => 'Mr.',
        1 => 'Mrs.',
      ),
      2 => 
      array (
        0 => ' ',
      ),
      3 => 
      array (
        0 => 'Alvin',
        1 => 'Dale',
      ),
      4 => 
      array (
        0 => '! Good Morning!',
      ),
    )
    

    See a PHP demo