Belgin Fish
Belgin Fish

Reputation: 19837

Explode that doesn't look inside parenthesis PHP

I have strings similar to the following

MATH 2822 or (PHYS 1939 and PHYS 1238)
MATH 2881 and (CHEM 2184 or PHYS 1000)
MATH 2881 and (CHEM 2184 or PHYS 1000) or ELEC 2921
MATH 2881 and ELEC 2921

Essentially I want to do an explode() on them to split up the requirements, but the explode should not affect anything inside the parenthesis.

For example:

$str = MATH 2881 and (CHEM 2184 or PHYS 1000) or ELEC 2921
/* explode on "or" result as follows */
$arr[0] = Math 2881 and (CHEM 2184 or PHYS 1000)
$arr[1] = ELEC 2921

As you can see, it shouldn't split up the two elements inside the parenthesis.

What would be a good way to do this?

Upvotes: 1

Views: 100

Answers (1)

user2782001
user2782001

Reputation: 3488

You could use multiple explodes and look for the parentheses.

explode with "(" as a parameter.

That should give you an array that looks like

$arr[0] = Math 2881 and;
$arr[1] = CHEM 2184 or PHYS 1000) ELEC 2921;

then explode $arr[1] with ")" as a parameter which you can get as new variables

$Narr[0]=CHEM 2184 or PHYS 1000;
$Narr[1]=or ELEC 2921;

Then you can put them in a finished array $FINarr=array(0=>$arr[0],1=>$Narr[0],2=>$Narr[1]);

$FINarr[0]=Math 2881 and;
$FINarr[1]=HEM 2184 or PHYS 1000;
$FINarr[2]=or ELEC 2921;

Upvotes: 1

Related Questions