Last active
December 18, 2020 08:07
-
-
Save AlexQin2017/0a235a1f046d7d54a509842ad26c20e5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 两个字符串例子 | |
$str1 = 'a1=1&&a2=2&&a3=3&&(a4=1||a5=2||(a6=3&&a7=4))'; | |
$str2 = 'a1==1 && a2==3 && ((a4a5+(a6+a7)/3)>10 || (a1 /((a2/100)(a2/100))) >= 28 || (a3*((a1)+(a4-a5)+(a2))>4) ) && a10==6 || a9==9 && (a3>4 || a5 <6)'; | |
preg_match_all('/[^&|^\|]+/', $str2, $match);//提取 &&或者||符号中间的内容。 | |
if (!empty($match[0])) { | |
foreach ($match[0] as &$value) { | |
$value = trim(removeBrackets($value));//移除多余的括号 | |
} | |
} | |
echo(json_encode($match[0])); | |
/** | |
* 移除多余的括号 | |
* @param $string | |
* @return string|string[]|null | |
*/ | |
function removeBrackets($string) | |
{ | |
// 左括号 右括号 默认 0个 | |
$leftBracket = $rightBracket = 0; | |
// 计算括号个数 | |
for($i=0;$i<strlen($string);$i++){ | |
if ($string[$i] == '(') { | |
$leftBracket++; | |
} elseif ($string[$i] == ')') { | |
$rightBracket++; | |
} | |
} | |
$abs = abs($leftBracket - $rightBracket);//括号个数的差值 | |
if ($abs == 0) { | |
return $string; | |
} | |
if ($leftBracket > $rightBracket) {// 如果 左括号多,移除多余的 | |
$string = preg_replace('/\(/', '', $string, $abs); | |
} elseif ($leftBracket < $rightBracket) {// 如果 右括号多,移除多余的 | |
$string = preg_replace('/\)/', '', $string, $abs); | |
} | |
return $string; | |
} | |
############# | |
结果如下 | |
PS:第二个和你期待的有一点点不一样,但是我觉得应该也符合你预期。 | |
[ | |
"a1=1", | |
"a2=2", | |
"a3=3", | |
"a4=1", | |
"a5=2", | |
"a6=3", | |
"a7=4" | |
] | |
[ | |
"a1==1", | |
"a2==3", | |
"(a4a5+(a6+a7)/3)>10", | |
"(a1 /((a2/100)(a2/100))) >= 28", | |
"(a3*((a1+(a4-a5)+(a2))>4) )", | |
"a10==6", | |
"a9==9", | |
"a3>4", | |
"a5 <6" | |
] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment