preg_split逗号不在括号内 [英] preg_split commas not inside parenthesis

查看:89
本文介绍了preg_split逗号不在括号内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

测试字符串:

 有机全麦面包,蒙特利杰克奶酪(牛奶,奶酪文化,食盐),荷美尔天然火腿(盐,turbinado糖,乳酸(不是来自牛奶)

所需产量:

 数组(
[0] =>有机全麦面包
[1] => gt蒙特里杰克奶酪
[2] =>荷美尔天然火腿

我不在乎如果子成分与原始项目一起出现(即蒙特雷·杰克奶酪(牛奶,奶酪文化,盐)),我只是不想自己添加它们,因为它们没有添加成分。



我在这里发现了一些其他问题,尝试将其应用于我的问题,但我没有得到预期的输出。



哦,以防preg_split不是以PHP为中心的,我使用的是PHP。



预先感谢!

解决方案

我首先删除所有括号和eir内容:

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

,然后在其余的 preg_split()逗号。



如果可以嵌套括号,那么您将需要使用嵌套级别进行多次操作。



每次,最里面的括号都会被删除。


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!

解决方案

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.

这篇关于preg_split逗号不在括号内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆