小编use*_*840的帖子

PHP - 字符串逻辑分析 - "X和Y或Z"

我想采用一个未知长度的和/或逻辑查询查询字符串:

$logic = 'elephants and tigers or dolphins and apes or monkeys and humans and gorillas and and 133322 or 2';
Run Code Online (Sandbox Code Playgroud)

并将其解析为数组,我假设看起来像:

$parsed_to_or = array(
  array('elephants', 'tigers'),
  array('dolphins', 'apes'),
  array('monkeys', 'humans', 'gorillas', '133322'),
  array('2')
 );
Run Code Online (Sandbox Code Playgroud)

这是我到目前为止:

 $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;
  }
 } …
Run Code Online (Sandbox Code Playgroud)

php string parsing

8
推荐指数
1
解决办法
326
查看次数

标签 统计

parsing ×1

php ×1

string ×1