user5532254
user5532254

Reputation: 11

Split string into words in php

I want to split string which contains braces e.g.

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)}]"

and output will be :

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)}]
)

Upvotes: 0

Views: 189

Answers (3)

Avinash Raj
Avinash Raj

Reputation: 174874

You may try this,

preg_split('~(?:\[.*?\]|\(.*?\)|\{.*?\})(*SKIP)(*F)|,~', $str);
  • (?:\[.*?\]|\(.*?\)|\{.*?\}) matches all the bracketed blocks.
  • (*SKIP)(*F) makes the previous match to fail.
  • , Now it matches comma from the remaining string.

DEMO

Upvotes: 1

Mayur Koshti
Mayur Koshti

Reputation: 1862

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

Upvotes: 0

vks
vks

Reputation: 67998

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

You can use this.See demo.

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

Upvotes: 3

Related Questions