Sometimes we have a commission formula for each product, and the formula for calculating the commission is stored in the table in string format. When we use this calculation formula, it does not look like what we wrote: $ a=2 3*5; can easily calculate the result, and it is a string, so we must convert the string into a result that we can process
Sometimes we have There is a commission formula, and the formula for calculating the commission is stored in the table in string format. When we use this calculation formula, it is not as simple as what we wrote: $a=2 3*5; The result is output, and it is a string. Therefore, we must convert the string into a result that we can process
The eval() function in php can process php code, so this can be used to solve the problem: with a string The calculation formula stored in the format
, for example:
$str='2*(3+12)'; $result=eval("return $str;"); echo $result;
will output: 30
is the value of the expression
The return $str; in eval() is the PHP code
Of course, you can also bring in the value of the variable:
$a=3; $b=12; $str='2*($a+$b)'; $result=eval("return $str;"); echo $result;
Will output: 30
In this way, the code for implementing the calculator in PHP is implemented, mainly using the eval function of PHP.
The above is the entire content of this article, I hope it will be helpful to everyone's study.
Related recommendations:
PHP implementation for mixed Chinese and EnglishStringLength judgment and interception method
php str_getcsv implements the method of parsingstringinto an array
php custom function to implement statistics in ChineseStringLength method detailed explanation
The above is the detailed content of PHP implements string format calculation formula through eval. For more information, please follow other related articles on the PHP Chinese website!