Link to home
Start Free TrialLog in
Avatar of tonelm54
tonelm54

asked on

Split a sting into array

Im faily new to regex and want to know if you can specify a start and end.

For example I have a statment:-

((x=1) AND ((X=3)OR(x=4)))

What I want to do is break it up into its 2 elements:-
(x=1)
((X=3)OR(x=4))

And then split the second into its elements:-
(X=3)
(x=4)

I also want to find out what's in-between each of the statements eg OR or AND

Is this even possible using regex?

Thank you
Avatar of Marco Gasi
Marco Gasi
Flag of Spain image

With Php you could something like this:

$stmt = '((x=1) AND ((X=3)OR(x=4)))';

$andArray = explode('AND', $stmt);

$orArray = array();
foreach ($andArray as $arr){
  if (stristr($arr, 'OR')) {
    $orArray[] = explode('OR', $arr);
  }
}

Open in new window


This way you should get an array whose elements are divided by AND an array whose elements are divided by OR
Using preg_split:

$stmt = '((x=1) AND ((X=3)OR(x=4)))';
$regex = '#(AND|OR)#';
$result = preg_split($regex, $stmt);
print_r($result); 

Open in new window

Regex is about matching patterns of characters, and a pattern doesn't necessarily need to repeat. You simply need to specify the pattern (or template if you wish) that the regex engine should look for.

You have given a very specific example, but I suspect that the need for this will be much more generic. What are the rules for what you intend to match? Is it only "((x=1) AND ((X=3)OR(x=4)))", or are any parts of that string variable?


@marqusG

Your preg_split example does not satisfy the requirement:

I also want to find out what's in-between each of the statements eg OR or AND
ASKER CERTIFIED SOLUTION
Avatar of Marco Gasi
Marco Gasi
Flag of Spain image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial