PHP计算字符串中的公式 [英] php calculate formula in string
问题描述
所以我将公式作为字符串
So I have formula as string
$comm = "(a x 5% - 2%)";
我希望它是$comm = $a * 5/100 * (1-2/100);
如何在php中做到这一点?
How can I do this in php?
推荐答案
要从头开始可靠且安全地以正确的方式执行此操作,则需要执行以下操作:
To do this the right way, reliably and safely, from scratch, you will need to perform:
-
词法分析,这涉及将输入与标记进行模式匹配:
Lexical analysis, this involves pattern matching the input with tokens:
(a x 5% - 2%)
将变成以下令牌链之类的东西:
would become something like the following chain of tokens:
openparen variable multiply integer percent minus integer percent closeparen
语法分析,这涉及获取这些标记并定义它们之间的关系,类似这样,匹配标记的模式:
Syntax analysis, this involves taking those tokens and defining the relationships between them, something like this, matching up the patterns of tokens:
statement = operand operator statement
然后,您将需要分析结果语法树,以便您可以运行它并产生答案.
Then you will need to parse the resulting syntax tree so that you can run it and produce the answer.
它看起来永远不会像$comm = $a * 5/100 - 2/100;
那样简单,但是会得出相同的结论.
It won't ever look as simple as $comm = $a * 5/100 - 2/100;
but it will result in the same conclusion.
某个地方的某人可能已经解决了这个问题,这是我经过简短的Google搜索后发现的两个: PHP数学表达式解析器, 另一个.
Someone somewhere has already likely had a go at this problem, here's two I found after a brief Google search: PHP Maths Expression Parser, And another.
这些SO问题也很相似数学解析器的智能设计?,在php中处理数学方程式
These SO questions are similar as well Smart design of a math parser?, Process mathematical equations in php
这篇关于PHP计算字符串中的公式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!