Search code examples
phpregexpreg-matchpcre

String to array, split by new lines and brackets


I have large string block which I need to split into arrays based on if they're wrapped in brackets or separated by new lines.

Input:

[this is block
this is also same "block"
this is same block

another same block]
new block!
another new block!
[this is new block
this is also a new block]

One of the many things I've tried:

$block_lines = preg_split('/\[([^]]+)\]|\r/', $block_content);

Expected result:

Array
(
  [0] => 'this is block
  this is also same "block"
  this is same block

  another same block'
  [1] => 'new block!'
  [2] => 'another new block!'
  [3] => 'this is new block
  this is also a new block'
)

Actual result:

Array
(
  [0] => 'new block!'
  [1] => 'another new block!'
  [2] => ''
)

Solution

  • You can use this regex in preg_split:

    /\[([^]]+)]|\R/
    

    It splits the string on either a string of characters inside [ and ], or on a newline. By using the PREG_SPLIT_DELIM_CAPTURE flag, we can capture the contents of the [] as well:

    $string = '[this is block
    this is also same "block"
    this is same block
    
    another same block]
    new block!
    another new block!
    [this is new block
    this is also a new block]';
    print_r(preg_split('/\[([^]]+)]|\R/', $string, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE));
    

    Output:

    Array ( 
        [0] => this is block 
    this is also same "block" 
    this is same block
    
    another same block
        [1] => new block!
        [2] => another new block!
        [3] => this is new block
    this is also a new block
    )
    

    Demo on 3v4l.org