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

ぃ、小莉子 提交于 2019-12-12 01:33:05

问题


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

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 >,<,>=,<=,==.


回答1:


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.



来源:https://stackoverflow.com/questions/3424245/how-to-manipulate-and-validate-string-containing-conditions-that-will-be-evaluat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!