如何使用PHP将字符串形式的数学表达式计算到输出?
<?php
$ma ="min(2+10,5*1,max(8/2,8-2,abs(-10)))"; // math expression
print $ma; // output of the calculation
?>
发布于 2018-11-01 22:47:48
我做了一个math_eval
帮助器函数包,应该可以做你想要的。
示例用法:
require 'vendor/autoload.php';
$two = math_eval('1 + 1');
$three = math_eval('5 - 2');
$ten = math_eval('2 * 5');
$four = math_eval('8 / 2');
链接:https://github.com/langleyfoxall/math_eval
在后台,它包装了mossadal/math parser包。
发布于 2018-08-13 20:25:20
你可以使用PHP eval()函数来处理数学表达式。eval()函数只支持PHP代码,而不支持精确的数学表达式。因此,eval()函数中使用的数学表达式字符串应该是有效的PHP代码,您可以使用
$ma = "min(2+10,5*1,max(8/2,8-2,abs(-10)))";
$result= eval('return '.$ma.';');
print $result;
发布于 2018-08-13 22:31:15
我在GitHub上发现了一些解析器,这个看起来非常有趣:
mossadal/math-parser: PHP parser for mathematical expressions
它可以这样使用:
use MathParser\StdMathParser;
use MathParser\Interpreting\Evaluator;
$parser = new StdMathParser();
// Generate an abstract syntax tree
$AST = $parser->parse('1+2');
// Do something with the AST, e.g. evaluate the expression:
$evaluator = new Evaluator();
$value = $AST->accept($evaluator);
echo $value;
它还可以与cos()
或sin()
等函数一起使用。
https://stackoverflow.com/questions/51816310
复制相似问题