Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic logical expression parsing/evaluation in PHP?

Tags:

php

parsing

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?

like image 989
cletus Avatar asked Nov 29 '08 02:11

cletus


2 Answers

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

like image 153
Christian C. Salvadó Avatar answered Oct 31 '22 10:10

Christian C. Salvadó


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

like image 12
Cam Avatar answered Oct 31 '22 08:10

Cam