问题
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