Dynamic logical expression parsing/evaluation in PHP?

前端 未结 6 443
隐瞒了意图╮
隐瞒了意图╮ 2021-01-11 14:10

I have a need to evaluate user-defined logical expressions of arbitrary complexity on some PHP pages. Assuming that form fields are the primary variables, it would need to:

相关标签:
6条回答
  • 2021-01-11 14:29

    You can try adapting my Evaluator class (https://github.com/djfm/Evaluator), it does arithmetic expressions (for now) and you can use variables too. All the major PHP operators are implemented.

    0 讨论(0)
  • 2021-01-11 14:30

    Check create_function, it creates an anonymous function from the string parameters passed, I'm not sure about its performance, but it's very flexible...

    0 讨论(0)
  • 2021-01-11 14:32

    If I understand the problem correctly, you want the users to write out functions in non-PHP, and then have PHP interpret it?

    If so, you could simply take their string and replace "lt" with "<" and "gt" with ">" ... then do eval().

    I have a hunch the problem isn't this simple, but if it is, eval() could do the job. Of course, then you're opening yourself up for any kind of attack.

    0 讨论(0)
  • 2021-01-11 14:47

    Take a look at my infix to postfix example I think you could port it to PHP with relative ease. It only uses an array and some switches. No trees. A stack is only needed to run the postfix result.

    0 讨论(0)
  • 2021-01-11 14:48

    Much time has gone by since this question was asked, and I happened to be looking for an expression parser for php. I chose to use the ExpressionLanguage component from Symfony 2.4. It can be installed with no dependencies from composer via packagist.

    composer require symfony/expression-language

    0 讨论(0)
  • 2021-01-11 14:48

    Check out this function: http://pluginphp.com/plug-in31.php

    0 讨论(0)
提交回复
热议问题