我想利用一个和/或未知长度的逻辑查询查询字符串:PHP - 字符串逻辑解析 - “X AND Y OR Z”
$logic = 'elephants and tigers or dolphins and apes or monkeys and humans and gorillas and and 133322 or 2';
它解析成一个数组,我假定将看起来是这样的:
$parsed_to_or = array(
array('elephants', 'tigers'),
array('dolphins', 'apes'),
array('monkeys', 'humans', 'gorillas', '133322'),
array('2')
);
这是我到目前为止有:
$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();
}
任何更好的办法来解决呢?
没有括号布尔*语言*没有多大意义。 – hek2mgl 2013-05-08 15:00:45
在'或'上爆炸(')它会不会更容易,然后爆炸'和'上的每个片段?无可否认,这会给你一个空的数组,在你的样本字符串的末尾,你有“和和”,但你可以检查。 – andrewsi 2013-05-08 15:03:05
是“和和”结尾的错字吗? – 2013-05-08 15:05:51