PHP – 字符串逻辑分析 – “X和Y或Z”
发布时间:2020-12-13 18:18:56 所属栏目:PHP教程 来源:网络整理
导读:我想采用未知长度的和/或逻辑查询查询字符串: $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'),a
|
我想采用未知长度的和/或逻辑查询查询字符串:
$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();
}
有没有更好的方法来解决这个问题?
更新:添加了使用&& ;;的功能和||随地
您可以执行以下操作: <?php
$logic = 'elephants && tigers || dolphins && apes || monkeys and humans and gorillas and && 133322 or 2';
$result = array();
foreach (preg_split('/ (or|||) /',$logic) as $parts) {
$bits = preg_split('/ (and|&&) /',$parts);
for ($x=0; $x<count($bits); $x++) {
$bits[$x] = preg_replace('/s?(and|&&)s?/','',$bits[$x]);
}
$result[] = $bits;
}
echo '<pre>';
var_dump($result);
这将导致以下结果: array(4) {
[0]=>
array(2) {
[0]=>
string(9) "elephants"
[1]=>
string(6) "tigers"
}
[1]=>
array(2) {
[0]=>
string(8) "dolphins"
[1]=>
string(4) "apes"
}
[2]=>
array(4) {
[0]=>
string(7) "monkeys"
[1]=>
string(6) "humans"
[2]=>
string(8) "gorillas"
[3]=>
string(6) "133322"
}
[3]=>
array(1) {
[0]=>
string(1) "2"
}
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
