在php中将字符串拆分为单词

时间:2015-11-06 06:15:48

标签: php regex

我想拆分包含大括号的字符串 例如

string = "some-thing_text,text in rounded brackets(word first,word second),Text in curly brackets{some-text(some one,some two),some another},Text in square brackets[some text,some another{some like this(this1,this2)}]"

并输出:

Array
(
    [0] => some-thing_text
    [1] => text in rounded brackets(word first,word second)
    [2] => Text in curly brackets{some-text(some one,some two),some another}
    [3] => Text in square brackets[some text,some another{some like this(this1,this2)}]
)

3 个答案:

答案 0 :(得分:3)

,(?![^{]*})(?![^(]*\))(?![^\[]*\])

你可以使用它。参见演示。

https://regex101.com/r/lR1eC9/8

答案 1 :(得分:1)

你可以试试这个,

preg_split('~(?:\[.*?\]|\(.*?\)|\{.*?\})(*SKIP)(*F)|,~', $str);
  • (?:\[.*?\]|\(.*?\)|\{.*?\})匹配所有括号内的块。
  • (*SKIP)(*F)使上一场比赛失败。
  • ,现在它与剩余字符串中的逗号匹配。

DEMO

答案 2 :(得分:0)

preg_split('~,(?![^{]*}|[^(]*\)|[^\[]*\])~', $string)