开发者

How to manipulate and validate string containing conditions that will be evaluated by php

Part of the program I am creating consists of the user creating conditions which I will store in a mysql database. I want the syntax to be somewhat easier than what php allows but since this will ultimately be run as php code using eval() it needs to have valid syntax.

For example:

User Input:

4<var1<=9 AND var2<6
开发者_JS百科

Result should be:

4<var1 AND var1<=9 AND var2<6

Before this is eval'd I surround it with an if statement that simply returns true.

What would be a good way to detect and split that comparison up?

Also, how can I test that the resulting code will not cause any php errors so that if it will I can inform the user?

Edit: To be clear those conditions can be any standard conditions such as >,<,>=,<=,==.


Even a more user friendly approach will be an interface like Treffynnon says, an initial approach to parse the string would be:

  1. split string by spaces (asuming spaces are required)
  2. traverse the resulting array
  3. the items that don't contain AND nor OR are conditions, split them by any of the logic operators (>,>, >=, <=, ==, !=)
  4. Now you got all the sintax parsed, it's ready for interpretation.

This would be an example (not tested, consider it pseudocode) $tokens = explode(' ', $user_string);

$to_evaluate = array();
foreach( $tokens AS $tok )
{
     if( $tok!='AND' && $tok!='OR' )
     {
         $parts = preg_split("/(<|>|<=|>=|==|!=)+/", $tok);
         if( count($parts)==3 )
         {
             $to_evaluate[] = array( 'element1'=>$parts[0], 'condition'=>$parts[1], 'element2'=>$parts[2] );
         }
         else
             echo "¿Error?";
     }
     else
        $to_evaluate[] = $tok;
}

At this point you must traverse $to_evaluate and start evaluating each condition you found.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜