0

I have a txt file with hundreds of logical expressions. I want to read each one (no problem so far) and to be able to evaluate it recursively, but I can't figure a way how. The expression has && and == and comparissons between strings and numbers. I don't want to use eval, as it's not recommended apparently and it didn't work in my case.

Example. Let's say I read these 2 strings:

s = "a == alpha && b == beta || b == omega", or
s = "g >= 2 && f != gamma"

I want to break them down to

($a == "alpha" && $b == "beta" || b == "omega")
($g >= 2 && f!= "gamma")

to use them in an if, so that it returns TRUE or FALSE. My problem is not with replacing the variables, it's with making them evaluate as a logical expression

Can anybody give me a hand?

Thanks in advance, Cristina

Cristina
  • 77
  • 8
  • What is your problem ??? Placing the Actual Values in this Expression?? For Examle:this is the Input- a == alpha && b == beta || b == omega and you want this 1==1 && 2==2 || 3==3 – CyberBoy Sep 04 '15 at 10:30
  • Placing the value is not a problem. Evaluating the expression is. Since this is a string, it dosn't evaluate. – Cristina Sep 04 '15 at 10:32
  • What i understood is this : if( (($a == 'alpha' && $b == 'beta') || ($b == 'omega')) || ($g >= 2 && $f != 'gamma')) { // do something } else { // do something } where $a, $b,$g,$f are the variables – Happy Coding Sep 04 '15 at 10:35
  • Using [eval](http://php.net/manual/en/function.eval.php) is your best bet, but you still hve to rework the string to normal php code – Michel Sep 04 '15 at 10:36
  • You made an edit. I had understood it right. (a == alpha && b == beta || b == omega) to ($a == "alpha" && $b == "beta" || b == "omega") and finally after substituting value of variable it will look like - (1=='alpha' && 2=='beta' || 3=='omega') – CyberBoy Sep 04 '15 at 10:41

1 Answers1

-2

Try this :

if( (($a == 'alpha' && $b == 'beta') || ($b == 'omega')) || ($g >= 2 && $f != 'gamma'))
{
    // returns true
}
else
{
    // returns false
}
Happy Coding
  • 2,517
  • 1
  • 13
  • 24
  • The string is not always the same. The idea is to create a function that knows how to evaluate this kind of strings. – Cristina Sep 04 '15 at 10:46