Validate user inputted PHP code before passing it to eval()

前端 未结 5 1235
傲寒
傲寒 2021-01-12 10:10

Before passing a string to eval() I would like to make sure the syntax is correct and allow:

  1. Two functions: a() and b()
  2. Four operators: /*-+
5条回答
  •  情深已故
    2021-01-12 10:15

    yes, you need the Tokenizer, or something similar, but it's only part of the story. A tokenizer (more commonly called "lexer") can only read and parse elements of an expression, but has no means to detect that something like "foo()+*bar)" is invalid. You need the second part, called parser which would be able to arrange tokens in a kind of a tree (called "AST") or provide an error message when failing to do so. Ironically, once you've got a tree, "eval" is not needed anymore, you can evaluate your expression directly from the tree.

    I would recommend you to write a parser by hand because it's a very useful exercise and a lot of fun. Recursive descent parsers are quite easy to program.

提交回复
热议问题