Search code examples
phpboolean-logic

Evaluate logic expression given as a string in PHP


I have an object which has a state property, for example state = 'state4' or state = 'state2'.

Now I also have an array of all available states that the state property can get, state1 to state8 (note: the states are not named stateN. They have eight different names, like payment or canceled. I just put stateN to describe the problem).

In addition to that, I have a logical expression like $expression = !state1||state4&&(!state2||state5) for example. This is the code for the above description:

$state = 'state4';
$expression = '!state1||state4&&(!state2||state5)';

Now I want to check if the logical expression is true or false. In the above case, it's true. In the following case it would be false:

$state = 'state1';
$expression = state4&&!state2||(!state1||state7);

How could this be solved in an elegant way?


Solution

  • //Initialize
    $state = 'state4';
    $expression = '!state1||state4&&(!state2||state5)';
    
    //Adapt to your needs
    $pattern='/state\d/';
    
    //Replace
    $e=str_replace($state,'true',$expression);
    while (preg_match_all($pattern,$e,$matches)
       $e=str_replace($matches[0],'false',$e);
    
    //Eval
    eval("\$result=$e;");
    echo $result;
    

    Edit:

    Your update to the OQ necessitates some minor work:

    //Initialize
    $state = 'payed';
    $expression = '!payed||cancelled&&(!whatever||shipped)';
    
    //Adapt to your needs
    $possiblestates=array(
       'payed',
       'cancelled',
       'shipped',
       'whatever'
    );
    
    //Replace
    $e=str_replace($state,'true',$expression);
    $e=str_replace($possiblestates,'false',$e);
    
    //Eval
    eval("\$result=$e;");
    echo $result;
    

    Edit 2

    There has been concern about eval and PHP injection in the comments: The expression and the replacements are completly controlled by the application, no user input involved. As long as this holds, eval is safe.