Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string into executable expression PHP?

I am working on Expression Builder, where user can add many rules.

I am trying to convert rules into the one expression, but PHP always consider as string and always return true.

Is there any way to make that expression executable?

public function translate($record = null){
        $rule = $this->rule;
        $conditions = [];
        if( count($rule->rules) ){
            $last_key = key( array_slice( $rule->rules, -1, 1, TRUE ) );
            foreach ($rule->rules as $key => $value) {
                $conditions[] = '"'.$record->{$value->field} .'" ' . $this->operator($value->operator) .' "'. $value->value.'"';
            }
        }

        $condition = implode(' '.$rule->condition.' ', $conditions);

        return $condition;// result : "Full Packaged Product" == "Full Packaged Product" AND "No" != "Y"
    }

// using here

foreach( $records as $ind => $record ){
            foreach( $rules as $rule){
                // $condition = $rule->translate(collect($record));
                $condition = $rule->translate($record);
                if($condition){
                    dump('Pass', $condition);
                }else{
                    dump('Fail', $condition);
                }
            }
        }

Also I tried to use eval() PHP function, but no luck!

Thanks, Kaleem

like image 980
Kaleem Avatar asked Dec 06 '25 16:12

Kaleem


1 Answers

You could use eval() if you're sure that code is safe.

Usage:

eval('$res = "yes" == "no" ;'); 
var_dump($res); // bool(false)
like image 187
Syscall Avatar answered Dec 08 '25 05:12

Syscall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!