Shiromi
Shiromi

Reputation: 157

Replace placeholders in a template string using correlated values from another dataset

I have two tables. One is RuleSet and another is Logic. Let's say my RuleSet table contains a row as [(R1 AND R2) OR R3], and the Logic table contains the logic of each rule. Something like:

R1 | x > 4  
R2 | y < 9
R3 | z < 5

I do want to replace the logic value in relevant place (something like [((x > 4) AND (y < 9 )) OR (z < 5)] ) to execute. How can I achieve it?

Upvotes: 0

Views: 56

Answers (1)

Ties Vandyke
Ties Vandyke

Reputation: 154

I do not fully get the question, but you i think you are trying to do a compare based on a string variable you fetched from a database.

If this is the case:

<?php

$logic_rule = "(R1 AND R2) OR R3"; // SELECT * FROM `myrules` WHERE etc
$x=1;
$y=2;
$z=3;

/* fetch data and iratate with a foreach // SELECT * FROM `conditions` WHERE etc */
$logic_rule = str_replace("R1", "x > 4",$logic_rule);
$logic_rule = str_replace("R2", "y < 9",$logic_rule);
$logic_rule = str_replace("R3", "z < 5",$logic_rule);
/* $logic_rule is now: $logic_rule = "(x > 4 AND y < 9) OR z < 5"; */

/* replace variables (or place in array and foreach the array) */
$logic_rule = str_replace("x", $x,$logic_rule);
$logic_rule = str_replace("y", $y,$logic_rule);
$logic_rule = str_replace("z", $z,$logic_rule);
/* $logic_rule is now: $logic_rule = "(1 > 4 AND 2 < 9) OR 3 < 5"; */

/*Test the condition:*/
var_dump (eval ("return (".$logic_rule.");")); // true

Upvotes: 2

Related Questions