php - calculate math expression from a string using eval
I want to calculate math expression from a string. I have read that the solution to this is to use eval(). But when I try to run the following code:
<?php
$ma ="2+10";
$p = eval($ma);
print $p;
?>
It gives me the following error:
Parse error: syntax error, unexpected $end in C:\xampp\htdocs\eclipseWorkspaceWebDev\MandatoryHandinSite\tester.php(4) : eval()'d code on line 1
Does someone know the solution to this problem.
Answer
Solution:
While I don't suggest using
eval
for this (it is not the solution), the problem is thateval
expects complete lines of code, not just fragments.Should do what you want.
A better solution would be to write a tokenizer/parser for your math expression. Here's a very simple regex-based one to give you an example:
Answer
Solution:
Take a look at this..
I use this in an accounting system where you can write math expressions in amount input fields..
Examples
Code
Answer
Solution:
I recently created a PHP package that provides a
math_eval
helper function. It does exactly what you need, without the need to use the potentially unsafeeval
function.You just pass in the string version of the mathematical expression and it returns the result.
You can also pass in variables, which will be substituted if needed.
Link: https://github.com/langleyfoxall/math_eval
Answer
Solution:
Using eval function is very dangerous when you can't control the string argument.
Try Matex for safe Mathematical formulas calculation.
Answer
Solution:
Solved!
Answer
Solution:
This method has two major drawbacks:
Security, php script is being evaluated by the eval function. This is bad, especially when the user wants to inject malicious code.
Complexity
I created this, check it out: Formula Interpreter
How does it work ?
First, create an instance of
FormulaInterpreter
with the formula and its parametersUse the
execute()
method to interpret the formula. It will return the result:in a single line
Examples
About the formulas
You can improve it if you want to!
Answer
Solution:
eval
Evaluates the given code asPHP
. Meaning that it will execute the given paremeter as a PHP piece of code.To correct your code, use this :
Answer
Solution:
Answer
Solution:
An eval'd expression should end with ";"
Try this :
By the way, this is out of scope but the 'eval' function won't return the value of the expression. eval('2+10') won't return 12. If you want it to return 12, you should eval('return 2+10;');