开发者

preg_split commas not inside parenthesis

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 开发者_StackOverflow中文版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!


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜