views:

255

answers:

1

Test string:

Organic whole wheat bread, Monterey Jack Cheese (milk, cheese culture, salt), Hormel Natural Ham (salt, turbinado sugar, lactic acid (not from milk)

Desired output:

Array ( 
        [0] => Organic whole wheat bread 
        [1] => Monterey Jack Cheese
        [2] => Hormel Natural Ham
      )

I don't mind if the sub-ingredients appear with the original item (i.e., "Monterey Jack Cheese (milk, cheese culture, salt)"), I just don't want them on their own because they aren't added ingredients.

I found a couple other questions here that I tried applying to my problem, but I never got the expected output.

Oh, and in case preg_split isn't PHP-centric, I'm using PHP.

Thanks in advance!

A: 

I would first remove all the parentheses and their contents:

$result = preg_replace('/\s*\([^()]+\)/', '', $subject);

and then preg_split() on the remaining commas. This assumes that parentheses aren't nested.

If parentheses can be nested, then you will need to run this as many times as there are nesting levels. Each time, the innermost parenthesis will be removed.

Tim Pietzcker
Code: $ingredients = explode(',',preg_replace('/\s*\([^()]+\)/', '', $list));This is the output I'm getting: Array ( [0] => Organic whole wheat bread [1] => Monterey Jack Cheese [2] => Hormel Natural Ham (salt [3] => turbinado sugar [4] => lactic acid ) It's only replacing the first one.
Stephane
preg_replace_all doesn't exist. Are you suggesting I use preg_match_all?preg_replace should replace all matches, which I why I'm confused.
Stephane
double-parens were the problem. Thank you and happy new year.
Stephane