所以我有公式作为字符串
$comm = "(a x 5% - 2%)";
我希望它是 $comm = $a * 5/100 * (1-2/100);
我怎样才能在 php 中做到这一点?
看一眼
http://www.phpclasses.org/package/2695-PHP-Safely-evaluate-mathematical-expressions.html
哪个可以评估数学代码
// instantiate a new EvalMath
$m = new EvalMath;
$m->suppress_errors = true;
// set the value of x
$m->evaluate('x = 3');
var_dump($m->evaluate('y = (x > 5)'));
发现于: 在 php 中处理数学方程
要从头开始以正确、可靠和安全的方式执行此操作,您需要执行以下操作:
词法分析,这涉及将输入与标记进行模式匹配:
(a x 5% - 2%)
将变成类似于以下令牌链:
openparen variable multiply integer percent minus integer percent closeparen
语法分析,这涉及获取这些标记并定义它们之间的关系,就像这样,匹配标记的模式:
statement = operand operator statement
然后您将需要解析生成的语法树,以便您可以运行它并生成答案。
它永远不会看起来那么简单,$comm = $a * 5/100 - 2/100;
但它会得出相同的结论。
某个地方的某个人可能已经解决了这个问题,这是我在简短的 Google 搜索后发现的两个: PHP Maths Expression Parser和 另一个.
这些 SO 问题也很相似数学解析器的智能设计?,在 php 中处理数学方程
它只是尝试,但也许是好的开始。
$somm = 0;
$a = 30;
$str = "(a x 5% - 2%)";
$pt1 = "/x/i";
$str = preg_replace($pt1, "*", $str);
$pt2 = "/([a-z])+/i";
$str = preg_replace($pt2, "\$$0", $str);
$pt3 = "/([0-9])+%/";
$str = preg_replace($pt3, "($0/100)", $str);
$pt4 = "/%/";
$str = preg_replace($pt4, "", $str);
$e = "\$comm = $str;";
eval($e);
echo $e . "<br>";
echo $comm;
解决了!!
<?php
function evalmath($equation)
{
$result = 0;
// sanitize imput
$equation = preg_replace("/[^a-z0-9+\-.*\/()%]/","",$equation);
// convert alphabet to $variabel
$equation = preg_replace("/([a-z])+/i", "\$$0", $equation);
// convert percentages to decimal
$equation = preg_replace("/([+-])([0-9]{1})(%)/","*(1\$1.0\$2)",$equation);
$equation = preg_replace("/([+-])([0-9]+)(%)/","*(1\$1.\$2)",$equation);
$equation = preg_replace("/([0-9]{1})(%)/",".0\$1",$equation);
$equation = preg_replace("/([0-9]+)(%)/",".\$1",$equation);
/*if ( $equation != "" ){
$result = @eval("return " . $equation . ";" );
}
if ($result == null) {
throw new Exception("Unable to calculate equation");
}
return $result;*/
return $equation;
}
$total = 18000;
$equation = evalmath('total-(230000*5%-2%+3000*2*1)');
if ( $equation != "" ){
$result = @eval("return " . $equation . ";" );
}
if ($result == null) {
throw new Exception("Unable to calculate equation");
}
echo $result;
?>