douhuan1380
2010-05-26 21:08 阅读 34
已采纳

PHP preg_match数学函数

I'm writing a script that will allow a user to input a string that is a math statement, to then be evaluated. I however have hit a roadblock. I cannot figure out how, using preg_match, to dissallow statements that have variables in them.

Using this, $calc = create_function("", "return (" . $string . ");" ); $calc();, allows users to input a string that will be evaluated, but it crashes whenever something like echo 'foo'; is put in place of the variable $string.

I've seen this post, but it does not allow for math functions inside the string, such as $string = 'sin(45)';.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

4条回答 默认 最新

  • 已采纳
    doudao1369 doudao1369 2010-05-26 22:01

    For a stack-based parser implemented in PHP that uses Djikstra's shunting yard algorithm to convert infix to postfix notation, and with support for functions with varying number of arguments, you can look at the source for the PHPExcel calculation engine (and which does not use eval)

    Also have a look at the responses to this question

    点赞 评论 复制链接分享
  • douzhanyan5015 douzhanyan5015 2010-05-26 21:13

    How complex of a math function do you need to allow? If you only need basic math, then you might be able to get away with only allowing whitespace + the characters 0123456789.+/-* or some such.

    In general, however, using the language's eval-type capabilities to just do math is probably a bad idea.

    点赞 评论 复制链接分享
  • doumaoao0182 doumaoao0182 2010-05-26 22:03

    Something like:

    ^([\d\(\)\+\-*/ ,.]|sin\(|cos\(|sqrt\(|...)+$

    would allow only numbers, brackets, math operations and provided math functions. But it won't check if provided expression is valid, so something like +++sin()))333((( would be still accepted.

    点赞 评论 复制链接分享
  • douhuanchi6586 douhuanchi6586 2010-05-26 22:23

    I wonder if this class would help you? Found that doing a search on Google for "php math expressions".

    点赞 评论 复制链接分享

相关推荐