preg_split commas not inside parenthesis

泪湿孤枕 提交于 2020-01-21 21:14:11

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/1987341/preg-split-commas-not-inside-parenthesis

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!