开发者

PHP calculator with one input field

开发者 https://www.devze.com 2023-03-13 00:18 出处:网络
I need to have a text input field do or not do basic calculations.Example <input type=\"text\" />

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.


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.

reference site

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  


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 . + - * / ( )


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消