tags:

views:

1138

answers:

3

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:

  • substitute"varibles" for form fields values;
  • handle comparison operators, minimally ==, <, <=, >= and > by symbol, name (eg eq, lt, le, ge, gt respectively);
  • handle boolean operators not, and, or and possibly xor by name, symbol (eg !, &&, || and ^^ respectively);
  • handle literal values for strings and numbers;
  • be plaintext not XML (eg "firstname == '' or lastname == ''); and
  • be reasonably performant.

Now in years gone by I've written recursive descent parsers that could build an expression tree and do this kind of thing but thats not a task I'm relishing in PHP so I'm hoping there are things out there that will at least get me some of the way there.

Suggestions?

+1  A: 

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...

CMS
Ooooo nice. I'm no PHP expert so I wasn't aware of create_function. Thanks for that.
cletus
+1  A: 

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.

Thanks for the answer. The answer may in fact be that simple. I'm no PHP expert. Java is more my schtick. None of these expressions are coming from the outside world. Its all internal config.
cletus
A: 

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.

Guge