Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 143
  • Last Modified:

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
0
tonelm54
Asked:
tonelm54
  • 3
1 Solution
 
Marco GasiFreelancerCommented:
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
0
 
Marco GasiFreelancerCommented:
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

0
 
käµfm³d 👽Commented:
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
0
 
Marco GasiFreelancerCommented:
Yes, you're right, I forgot to add the flag:

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

Open in new window

0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now