I would like to take a and/or logic query query string of unknown length:
$logic = 'elephants and tigers or dolphins and apes or monkeys and humans and gorillas and and 133322 or 2';
And parse it into an array, I assume would look something like:
$parsed_to_or = array(
array('elephants', 'tigers'),
array('dolphins', 'apes'),
array('monkeys', 'humans', 'gorillas', '133322'),
array('2')
);
This is what I have so far:
$logic_e = preg_split('/\s+/', $logic);
$or_segments = array();
$and_group = array();
foreach($logic_e as $fragment) {
if (preg_match('/^(and|&&)$/i', $fragment)) {
continue;
} elseif (preg_match('/^(or|\\|\\|)$/i', $fragment)) {
if (count($and_group)>0) {
$or_segments[] = $and_group;
$and_group = array();
} continue;
} else {
$and_group[] = $fragment;
continue;
}
}
if (count($and_group)>0) {
$or_segments[] = $and_group;
$and_group = array();
}
Any better ways to tackle this?