Skip to content
Advertisement

PHP: Explode comma outside of brackets

Below is a string I’ve tried to explode only on comma’s outside of the first set of brackets.

Wheat Flour (2%) [Wheat Flour, Wheat Gluten, Calcium Carbonate, Iron, Niacin (B3), Thiamin (B1), Ascorbic Acid], Water, Yeast, Salt, Vegetable Oils (Palm, Rapeseed, oils (sunflower, rapeseed)), Soya Flour

1st Attempt

JavaScript

Which returns:

JavaScript

2nd Attempt

JavaScript

Returns:

JavaScript

The first attempt is the closest I’ve been able to get to the below output I’m trying to get.

JavaScript

Advertisement

Answer

You may use this PCRE regex for splitting:

JavaScript

RegEx Demo

Code:

JavaScript

Output:

JavaScript

RegEx Explained:

  • (?:: Start non-capture group
    • (((?:[^()]*|(?-1))*)): Recursive pattern to match a possibly nested (...) substring
    • |: OR
    • ([(?:[^][]*|(?-1))*]): Recursive pattern to match a possibly nested [...] substring
  • ):
  • (*SKIP)(*F): Skip and Fail this match i.e. retain this data in split result
  • |: OR
  • h*,h*: Match a comma surrounded with 0 or more whitespaces on either side
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement