How to make a calculator in PHP?

后端 未结 3 937
暖寄归人
暖寄归人 2020-11-22 13:43

I want to use PHP to calculate simple algebraic expressions like, 8*(5+1), entered via an tag by a normal user (which means,

3条回答
  •  清歌不尽
    2020-11-22 13:52

    I'd start by stripping the input of anything which shouldn't be in the expression (assuming you just want to allow add, subtract, multiply, divide, and no variables):

     $expr = preg_replace('/[^0-9+*\/-]/', '', $expr);
    

    and then, once I'm confident nothing dangerous remains in the user input, simply pass the itthrough eval() to evaluate the expression:

     $result = eval("return $expr;");
    

    No need to reinvent the wheel.

    Edited to incorporate Kolink's corrections. Thanks!

提交回复
热议问题