如何评估IF中的字符串?

时间:2016-03-02 18:12:16

标签: php regex parsing expression eval

我的字符串包含"$a==1||$b==2||$c==3"之类的条件。

如何使用IF语句评估此字符串(作为条件)?

4 个答案:

答案 0 :(得分:1)

您可以使用Eval function来评估它,但首先,您需要连接一些代码:

$yourString = "$a==1||$b==2||$c==3";
$evalString = "if(".$yourString .")return true;";
$evaluation = eval($evalString);

在上面的这种情况下,如果任何条款为真,则返回true。

OBS:变量$ a,$ b,$ c应在执行前声明。

答案 1 :(得分:0)

要评估此条件,您可以使用eval()。 例如:

2016-03-02 19:04:11.509  WARN 4476 --- [           main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'newsService' defined in file [C:\Users\Lukasz\IdeaProjects\NewsSystem_REST\build\classes\main\com\newssystem\lab\dao\NewsService.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [com.newssystem.lab.dao.NewsDao]: : No qualifying bean of type [com.newssystem.lab.dao.NewsDao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.newssystem.lab.dao.NewsDao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
2016-03-02 19:04:11.516  INFO 4476 --- [           main] o.apache.catalina.core.StandardService   : Stopping service Tomcat
2016-03-02 19:04:11.538 ERROR 4476 --- [           main] o.s.boot.SpringApplication               : Application startup failed

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'newsService' defined in file [C:\Users\Lukasz\IdeaProjects\NewsSystem_REST\build\classes\main\com\newssystem\lab\dao\NewsService.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [com.newssystem.lab.dao.NewsDao]: : No qualifying bean of type [com.newssystem.lab.dao.NewsDao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.newssystem.lab.dao.NewsDao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:185) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1143) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1046) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839) ~[spring-context-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538) ~[spring-context-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118) ~[spring-boot-1.3.2.RELEASE.jar:1.3.2.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:766) [spring-boot-1.3.2.RELEASE.jar:1.3.2.RELEASE]
    at org.springframework.boot.SpringApplication.createAndRefreshContext(SpringApplication.java:361) [spring-boot-1.3.2.RELEASE.jar:1.3.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:307) [spring-boot-1.3.2.RELEASE.jar:1.3.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1191) [spring-boot-1.3.2.RELEASE.jar:1.3.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1180) [spring-boot-1.3.2.RELEASE.jar:1.3.2.RELEASE]
    at com.newssystem.lab.NewsSystemApplication.main(NewsSystemApplication.java:24) [main/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_25]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_25]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_25]
    at java.lang.reflect.Method.invoke(Method.java:483) ~[na:1.8.0_25]
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144) [idea_rt.jar:na]
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.newssystem.lab.dao.NewsDao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1373) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1119) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1014) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:813) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
    ... 24 common frames omitted

你要小心使用eval()。我不建议使用它,除非你真的必须和你确信$条件不是任何人都可以篡改的。

答案 2 :(得分:0)

简单易行。试试这个

<?php

   $a="yes";
   $b="ok";
   $c="yes";

   if(($a=='yes') || ($b=='ok') || ($c=='yes')){
   echo "If a=yes or b=ok or c=yes you got this";
   } else {
   echo "You got this, because a!=yes or b!=ok or c!=yes";
   }
?>

答案 3 :(得分:0)

而不是使用eval() - 在你的上下文中可能只是将表达式限制为你想要/应该允许的内容的噩梦 - 你可以创建一个只能处理那些操作的解析器/词法分析器你想要的。
你可以,例如看一下梨包PHP_LexerGeneratorPHP_ParserGenerator。或者搜索stackoverflow以获取有关[php] parser的答案。

只是为了好玩:
PHP 7 introduced编译过程中的Abstract Syntax Treehttps://github.com/nikic/php-ast处的扩展将此AST层暴露给userland脚本。使用这个[a]限于php7 +,b)不清楚这个扩展是否会在将来维护,我只是通过谷歌找到它你可以设置一个解释器,例如。

<?php
$data = [
    ['a'=>5, 'b'=>6, 'c'=>7],
    ['a'=>5, 'b'=>6, 'c'=>3],
    ['a'=>5, 'b'=>2, 'c'=>7],
    ['a'=>1, 'b'=>6, 'c'=>7],
    ['a'=>1, 'b'=>2, 'c'=>7],
    ['a'=>7, 'b'=>2, 'c'=>3],
];
$expressions = [
    '$a==1||$b==2||$c==3',
    '($a==1&&$b==2)||$c==3',
    '$a==1&&($b==2||$c==3)'
];

foreach( $expressions as $x ) {
    $ep = new ExpressionParser($x);
    echo $x, "\r\n";
    foreach( $data as $scope ) {
        $result = $ep->eval( $scope );
        printf(
            "   %s => %s\r\n", 
            compact_var_export($scope),
            compact_var_export($result)
        );
    }
}

class ExpressionParser {
    public function __construct($expr) {
        $ast = ast\parse_code('<?php '.$expr.';', $version=20);
        if (!$ast || ast\AST_STMT_LIST!=$ast->kind ) {
            throw new InvalidArgumentException('unable to parse expression');
        }
        else if ( 1!==count($ast->children) || ast\AST_BINARY_OP!==$ast->children[0]->kind ) {
            throw new InvalidArgumentException('only one binary expression allowed');
        }
        else {
            $this->ast = $ast->children[0];
        }
    }

    public function eval($scope) {
        return evalOp($scope, $this->ast);
    }
}

function evalOp($scope, $ast) {
    static $handler = null;

    if ( is_null($handler) ) {
        $handler = [
            ast\AST_UNARY_OP => [
                ast\flags\UNARY_BOOL_NOT    => function($scope, $c) { return !evalOp($scope, $c[0]); },
                ast\flags\UNARY_BITWISE_NOT => function($scope, $c) { return ~evalOp($scope, $c[0]); },
                ast\flags\UNARY_MINUS       => function($scope, $c) { return -evalOp($scope, $c[0]); },
            ],

            ast\AST_BINARY_OP => [
                ast\flags\BINARY_BOOL_AND            => function($scope, $c) { return evalOp($scope, $c[0]) && evalOp($scope, $c[1]); },
                ast\flags\BINARY_BOOL_OR             => function($scope, $c) { return evalOp($scope, $c[0]) || evalOp($scope, $c[1]); },
                ast\flags\BINARY_BOOL_XOR            => function($scope, $c) { return evalOp($scope, $c[0]) ^ evalOp($scope, $c[1]); },
                ast\flags\BINARY_IS_IDENTICAL        => function($scope, $c) { return evalOp($scope, $c[0]) === evalOp($scope, $c[1]); },
                ast\flags\BINARY_IS_NOT_IDENTICAL    => function($scope, $c) { return evalOp($scope, $c[0]) !== evalOp($scope, $c[1]); },
                ast\flags\BINARY_IS_EQUAL            => function($scope, $c) { return evalOp($scope, $c[0]) == evalOp($scope, $c[1]); },
                ast\flags\BINARY_IS_NOT_EQUAL        => function($scope, $c) { return evalOp($scope, $c[0]) != evalOp($scope, $c[1]); },
                ast\flags\BINARY_IS_SMALLER          => function($scope, $c) { return evalOp($scope, $c[0]) < evalOp($scope, $c[1]); },
                ast\flags\BINARY_IS_SMALLER_OR_EQUAL => function($scope, $c) { return evalOp($scope, $c[0]) <= evalOp($scope, $c[1]); },
                ast\flags\BINARY_IS_GREATER          => function($scope, $c) { return evalOp($scope, $c[0]) > evalOp($scope, $c[1]); },
                ast\flags\BINARY_IS_GREATER_OR_EQUAL => function($scope, $c) { return evalOp($scope, $c[0]) >= evalOp($scope, $c[1]); },
            ],

            ast\AST_VAR => function($scope, $a) {
                if ( !isset($scope[$a->children[0]]) ) {
                    throw new InvalidArgumentException('undefined variable: '.$a->children[0]);
                }
                else {
                    return $scope[$a->children[0]];
                }
            }
        ];
    }

    if ( !is_object($ast) ) {
        return $ast;
    }
    else if ( !isset($handler[$ast->kind]) ) {
        throw new InvalidArgumentException('unsupported operation type');
    }
    else if ( is_array($handler[$ast->kind]) ) {
        if ( !isset($handler[$ast->kind][$ast->flags]) ) {
            throw new InvalidArgumentException('unsupported operation');
        }
        else {
            return $handler[$ast->kind][$ast->flags]($scope, $ast->children);
        }
    }
    else {
        return $handler[$ast->kind]($scope, $ast);
    }
}

function compact_var_export($x) {
    return preg_replace('!\s+!m', ' ', var_export($x, true));
}

输出

$a==1||$b==2||$c==3
    array ( 'a' => 5, 'b' => 6, 'c' => 7, ) => false
    array ( 'a' => 5, 'b' => 6, 'c' => 3, ) => true
    array ( 'a' => 5, 'b' => 2, 'c' => 7, ) => true
    array ( 'a' => 1, 'b' => 6, 'c' => 7, ) => true
    array ( 'a' => 1, 'b' => 2, 'c' => 7, ) => true
    array ( 'a' => 7, 'b' => 2, 'c' => 3, ) => true
($a==1&&$b==2)||$c==3
    array ( 'a' => 5, 'b' => 6, 'c' => 7, ) => false
    array ( 'a' => 5, 'b' => 6, 'c' => 3, ) => true
    array ( 'a' => 5, 'b' => 2, 'c' => 7, ) => false
    array ( 'a' => 1, 'b' => 6, 'c' => 7, ) => false
    array ( 'a' => 1, 'b' => 2, 'c' => 7, ) => true
    array ( 'a' => 7, 'b' => 2, 'c' => 3, ) => true
$a==1&&($b==2||$c==3)
    array ( 'a' => 5, 'b' => 6, 'c' => 7, ) => false
    array ( 'a' => 5, 'b' => 6, 'c' => 3, ) => false
    array ( 'a' => 5, 'b' => 2, 'c' => 7, ) => false
    array ( 'a' => 1, 'b' => 6, 'c' => 7, ) => false
    array ( 'a' => 1, 'b' => 2, 'c' => 7, ) => true
    array ( 'a' => 7, 'b' => 2, 'c' => 3, ) => false

(我并不擅长这个。因此,专家可能会发现这个笨拙,有缺陷甚至是错误的;随意评论;-))