In the development, we will encounter some needs to configure the calculation formula, for example
We have configured a magnification and a calculation formula in the background, for example, the magnification is 3, the calculation formula is: %d*%d+100, which means a number multiplied by the magnification plus a supplementary value
So how should we deal with such a formula?
First of all, when you see the format of% d, you will definitely think of the sprintf() function, first use it to replace the corresponding variable
$num = 10; $double = 3; echo sprintf("%d*%d+100", $num, $double);
Execution will get the output: 10*3+100, although after this operation we get the calculation formula that our PHP can operate, but it is not the calculation result we want, but a string
The eval() function in PHP can execute strings as PHP code, so it can be used to solve calculation formulas in string format
$num = 10; $double = 3; $str = sprintf("%d*%d+100", $num, $double); eval("echo $str;");
This will get the calculation result we need: 130. If you need to return the value processed by eval instead of outputting it directly, you can modify echo to return.
So the question is, some students will say: Isn’t this function said to be dangerous? Didn’t you say that it can be used as a Trojan horse?
It does appear as a backdoor program. but! What I need to say here is: Although eval can execute arbitrary PHP code, this behavior of the Trojan horse is because it does not verify the data input by the user outside, and directly passes in any data provided by the user. At this time, there will be problems. , Such as calculation formulas are generally configured by back-end operators.
It should also be noted that when dealing with some floating-point number accuracy problems, you can use the BC mathematical function to ensure the accuracy of the operation.