Splitting Strings Containing Paired Brackets

Learn how to split a string containing pair brackets.

Suppose we have the input text provided below:

($one, $two, ($string .")" )), $three, hello,
"(this", "that )", $end($one, ($two))

And that we would like to split it into the array of strings as shown below:

array:6 [
  0 => "($one, $two, ($string .")" ))"
  1 => " $three"
  2 => " hello"
  3 => """
    
    "(this"
    """
  4 => " "that )""
  5 => " $end($one, ($two))"
]

However, if the entire input text is surrounded in parentheses, as shown below:

(($one, $two, ($string .")" )), $three, hello,
"(this", "that )", $end($one, ($two)))

We want to produce an array containing only a single value, which would be the input string:

array:1 [
  0 => """
    (($one, $two, ($string .")" )), $three, hello,
    "(this", "that )",
...

Get hands-on with 1400+ tech skills courses.