<?php
//@author Zjmainstay
//@website http://www.zjmainstay.cn
$str = 'TimeWhileTrue(aloop(({EngineSpeed}>1000)&&({EngineSpeed}<1800),5),5,10)&&ploop(\"{BATTERY_VOLTAGE_FILTERED}<=14.3\",5)<123*/-+\|aloop( \"{VVT_EXH_CAM_::_PCM_6CD6_006}<=1500\" ,10) > 20';
$expList = parseExp($str);
print_r($expList);
$matchList = getMatch($expList, '#[a-z\d_]+\(.*\)#i');
print_r($matchList);
$result = array();
foreach($matchList as $match) {
$result[] = empty($match[0]) ? '' : $match[0];
}
print_r($result);
/**
* 解析式子
* @param string $str 源字符串
* @return array
*/
function parseExp($str) {
$len = strlen($str);
$parseList = array();
$pair = 0; //为0表示配对成功,遇(加一,遇)减一
$expInit = false; //只有带()才算目标式子
$exp = ''; //当前式子
for($i = 0; $i < $len; $i++) {
$exp .= $str[$i]; //拼接当前字符(利用数组下标的方式获取字符串,类似 substr($str, $i, 1))
if($str[$i] == '(') { //左( 配对+1
$expInit = true;
$pair ++;
} else if($str[$i] == ')') { //右) 配对-1
$pair --;
} else if($expInit && $pair == 0) { //找到, 且配对成功,认为式子完成
$parseList[] = substr($exp, 0, -1); //去掉逗号
$exp = ''; //进入下一个式子匹配
$expInit = false;
}
}
if(!empty($exp) && $expInit && $pair == 0) {
$parseList[] = $exp;
}
return $parseList;
}
/**
* 获取式子匹配正则结果
* @param array $expList 式子数组
* @param string $pattern 正则
* @return array
*/
function getMatch($expList, $pattern) {
$matchList = array();
foreach($expList as $item) {
if(preg_match($pattern, $item, $match)) { //如果正则匹配成功,记录到命中数组
$matchList[] = $match;
}
}
return $matchList;
}