Reputation: 11342
I need to have a text input field do or not do basic calculations. Example
<input type="text" />
I then submit by post and the post will know to either enter the value or do calculations
Value examples
14.5
10.3+14+35
Should give me respectively
14.5
59.3
Does anyone know of a method, script,...anything to do this? Or any idea on how to go about it?
Thanks.
Upvotes: 4
Views: 2765
Reputation: 1
With the following regular expression you can check whether the input is valid mathematical syntax and use eval():
/^(\(*[\+\-]?\(*[\+\-]?\d+(.\d+)?\)*[\+\-\*\/]?)*$/
Allowed characters are: 1 2 3 4 5 6 7 8 9 0 . + - * / ( )
Upvotes: 0
Reputation: 23244
Without using eval but you still need to be careful and catch any parsing errors, for example trying to evaluate ')' etc. I have ideas but will leave them for the reader or another rainy day.
function calculate_string( $mathString ) {
// trim white spaces
$mathString = trim($mathString);
// remove any non-numbers chars; exception for math operators
$mathString = ereg_replace ('[^0-9\+-\*\/\(\) ]', '', $mathString);
$compute = create_function("", "return (" . $mathString . ");" );
return 0 + $compute();
}
$string = " (1 + 1) * (2 + 2)";
echo calculate_string($string); // outputs 8
Upvotes: 4
Reputation: 593
One quick solution would be to check with substr()
if the input has any math operators (+, -, ...) in it. If so, do the math either using eval()
(quite a dirty hack, since it accepts all PHP code and not only math) or build the appropriate tree of operations manually and then produce the results. If there are no math operators, just print out the input.
Upvotes: -1