PHP:括号内用逗号分隔 [英] PHP: Explode comma outside of brackets

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

问题描述

下面是我尝试仅在第一组括号之外的逗号爆炸的字符串.

Below is a string I've tried to explode only on comma's outside of the first set of brackets.

小麦粉(2%)[小麦粉,小麦面筋,碳酸钙,铁,烟酸(B3),硫胺素(B1),抗坏血酸],水,酵母,盐,植物油(棕榈,菜籽油),油(向日葵,油菜籽)),大豆粉

preg_split("/[\[\]|()]+/", "Wheat Flour (2%) [Wheat Flour, Wheat Gluten, Calcium Carbonate, Iron, Niacin (B3), Thiamin (B1), Ascorbic Acid], Water, Yeast, Salt, Vegetable Oils (Palm, Rapeseed, oils (sunflower, rapeseed)), Soya Flour", -1, PREG_SPLIT_NO_EMPTY);

哪个返回:

[0] => Wheat Flour 
[1] => 2%
[2] => Wheat Flour, Wheat Gluten, Calcium Carbonate, Iron, Niacin 
[3] => B3
[4] => , Thiamin 
[5] => B1
[6] => , Ascorbic Acid
[7] => , Water, Yeast, Salt, Vegetable Oils 
[8] => Palm, Rapeseed
[9] => , Soya Flour

第二次尝试

preg_split('/\|(?![^(]*\))/', "Wheat Flour (2%) [Wheat Flour, Wheat Gluten, Calcium Carbonate, Iron, Niacin (B3), Thiamin (B1), Ascorbic Acid], Water, Yeast, Salt, Vegetable Oils (Palm, Rapeseed, oils (sunflower, rapeseed)), Soya Flour");

返回:

[0] => Wheat Flour (2%) [Wheat Flour, Wheat Gluten, Calcium Carbonate, Iron, Niacin (B3), Thiamin (B1), Ascorbic Acid], Water, Yeast, Salt, Vegetable Oils (Palm, Rapeseed), Soya Flour

第一次尝试是最接近我要获取的以下输出.

The first attempt is the closest I've been able to get to the below output I'm trying to get.

[0] => "Wheat Flour (2%) [Wheat Flour, Wheat Gluten, Calcium Carbonate, Iron, Niacin (B3), Thiamin (B1), Ascorbic Acid]"
[1] => "Water"
[2] => "Yeast"
[3] => "Salt"
[4] => "Vegetable Oils (Palm, Rapeseed, oils (sunflower, rapeseed))"
[5] => "Soya Flour"

推荐答案

您可以使用此PCRE正则表达式进行拆分:

You may use this PCRE regex for splitting:

(?:(\((?:[^()]*|(?-1))*\))|(\[(?:[^][]*|(?-1))*\]))(*SKIP)(*F)|\h*,\h*

RegEx演示

代码:

$s = 'Wheat Flour [Wheat Flour, Wheat Gluten, Calcium Carbonate, Iron, Niacin (B3), Thiamin (B1), Ascorbic Acid], Water, Yeast, Salt, Vegetable Oils (Palm, Rapeseed, oils (sunflower, rapeseed)), Soya Flour';
$re = '~(?:(\((?:[^()]*|(?-1))*\))|(\[(?:[^][]*|(?-1))*\]))(*SKIP)(*F)|\h*,\h*~';

print_r(preg_split($re, $s));

输出:

Array
(
    [0] => Wheat Flour [Wheat Flour, Wheat Gluten, Calcium Carbonate, Iron, Niacin (B3), Thiamin (B1), Ascorbic Acid]
    [1] => Water
    [2] => Yeast
    [3] => Salt
    [4] => Vegetable Oils (Palm, Rapeseed, oils (sunflower, rapeseed))
    [5] => Soya Flour
)

正则表达式说明:

  • (?::启动非捕获组
    • (\((?:[^()] * |(?-1))* \)):递归模式以匹配可能嵌套的(...)子字符串
    • | :或
    • (\ [(?:[^] [] * |(?-1))* \]):递归模式以匹配可能嵌套的 [...] 子字符串
    • (?:: Start non-capture group
      • (\((?:[^()]*|(?-1))*\)): Recursive pattern to match a possibly nested (...) substring
      • |: OR
      • (\[(?:[^][]*|(?-1))*\]): Recursive pattern to match a possibly nested [...] substring

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

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