因为php函数 eval() 过于危险,为了方便计算字符串格式的运算公式,所以对 jiaych大拿的函数进行了改编,基本实现了类似 eval() 函数计算功能。贴代码:
/*******************四则运算计算器********************/
function maths($exp){
$arr_exp = [];
for($i=0;$i<strlen($exp);$i++){
if($exp[$i]=='+' || $exp[$i]=='-' || $exp[$i]=='*' || $exp[$i]=='/' || $exp[$i]=='(' || $exp[$i]==')'){
$arr_exp[] = $exp[$i];
}else{
if(end($arr_exp)=='+' || end($arr_exp)=='-' || end($arr_exp)=='*' || end($arr_exp)=='/' || end($arr_exp)=='(' || end($arr_exp)==')' || end($arr_exp)==''){
$arr_exp[] = $exp[$i];
}else{
$arr_exp[key($arr_exp)] = end($arr_exp).$exp[$i];
}
}
}
$result = calculator( array_reverse($arr_exp) );
return $result;
}
function calculator( $exp ){
$arr_n = [];
$arr_op = [];
while( ($s = array_pop( $exp )) != '' ){
if( $s == '(' ){
$temp = [];
$quote = 1;
$endquote = 0;
while( ($t = array_pop($exp)) != '' ){
if( $t == '(' ){
$quote++;
}
if( $t == ')' ){
$endquote++;
if( $quote == $endquote ){
break;
}
}
array_push($temp, $t);
}
$temp = array_reverse($temp);
array_push($arr_n, calculator($temp) );
}else if( $s == '*' || $s == '/'){
$n2 = array_pop($exp);
if( $n2 == '(' ){
$temp = array();
$quote = 1;
$endquote = 0;
while( ($t = array_pop($exp)) != '' ){
if( $t == '(' ){
$quote++;
}
if( $t == ')' ){
$endquote++;
if( $quote == $endquote )
break;
}
array_push($temp, $t);
}
$temp = array_reverse($temp);
$n2 = calculator($temp);
}
$op = $s;
$n1 = array_pop($arr_n);
switch ($op) {
case '+':
$result = $n1 + $n2;
break;
case '-':
$result = $n1 - $n2;
break;
case '*':
$result = $n1 * $n2;
break;
case '/':
$result = $n1 / $n2;
break;
}
array_push($arr_n, $result);
}else if( $s == '+' || $s == '-' ){
array_push($arr_op, $s);
}else{
array_push($arr_n, $s);
}
}
$n2 = array_pop($arr_n);
while( ($op = array_pop($arr_op)) != '' ){
$n1 = array_pop($arr_n);
switch ($op) {
case '+':
$n2 = $n1 + $n2;
break;
case '-':
$n2 = $n1 - $n2;
break;
case '*':
$n2 = $n1 * $n2;
break;
case '/':
$n2 = $n1 / $n2;
break;
}
}
return $n2;
}
调用方法:
$a = '1-7+8*(3+9)';
echo maths($a);
如有错误及bug欢迎指正!
其余
作为码农,推荐几个自己亲身使用过的云服务器平台给大家,感觉还不错有需要小伙伴自行查看:
1.阿里云:https://www.aliyun.com/?source=5176.11533457&userCode=mszy7nm5
2.腾讯云服务器:https://curl.qcloud.com/jgwhoTBS
另外偷偷透露一下,腾讯云的轻量服务器作简直不要太好,便宜、稳定、速度还够快。