preg_split 逗号不在括号内

发布于 2024-08-16 04:09:01 字数 551 浏览 4 评论 0原文

测试字符串:

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

所需的输出:

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

我不介意子成分是否与原始项目一起出现(即“蒙特利杰克奶酪(牛奶,奶酪文化,盐)”),我只是不想要它们单独存在,因为它们不是添加成分。

我在这里发现了其他几个问题,我尝试将其应用于我的问题,但我从未得到预期的输出。

哦,如果 preg_split 不是以 PHP 为中心,我正在使用 PHP。

提前致谢!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

魂归处 2024-08-23 04:09:01

我首先删除所有括号及其内容:

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

然后删除剩余的逗号上的 preg_split() 。这假设括号不是嵌套的。

如果括号可以嵌套,那么您将需要运行它与嵌套级别一样多的次数。每次,最里面的括号都会被删除。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文