PHP preg_split split by group 1

Viewed 80

I have these inputs:

Rosemary Hess (2018) (Germany) (all media)
Jackie H Spriggs (catering)

I want to split them by the first parentheses, the output i want:

array:2 [
  0 => "Rosemary Hess"
  1 => "(2018) (Germany) (all media)"
]

array:2 [
  0 => "Jackie H Spriggs"
  1 => "(catering)"
]

I tried these but not working correctly :

preg_split("/(\s)\(/", 'Rosemary Hess (2018) (Germany) (all media)')

But it splits every space with parentheses and returns five items rather two.

1 Answers

You can use

$strs= ["Rosemary Hess (2018) (Germany) (all media)", "Jackie H Spriggs (catering)"];
foreach ($strs as $s){
    print_r( preg_split('~\s*(?=\([^()]*\))~', $s, 2) );
}
// => Array ( [0] => Rosemary Hess [1] => (2018) (Germany) (all media) )
// => Array ( [0] => Jackie H Spriggs [1] => (catering) )

See the PHP demo. See the regex demo.

The preg_split third $limit argument set to 2 makes it split the string with the first occurrence of the pattern that matches:

  • \s* - 0+ whitespaces
  • (?=\([^()]*\)) - that are followed with (, 0 or more chars other than ( and ) and then a ).
Related