逻辑运算符表达式到PHP数组

时间:2018-04-24 07:10:06

标签: php logical-operators

我有像这样的表达式=> ({2606}或{2549}或{2543}或({2605}和{2562}))和({2387}或{2383}或{1990}或{2412}或{2411}或{2409}或( {2408}和{2593}))

我想要输出像这个数组。

[

"AND" => [ 

     "OR" => [ 2606, 2549, 2543, "AND" => [ 2605, 2562 ] ],
     "OR" => [ 2387, 2383, 1990, 2412, 2411, 2409, "AND" => [ 2408, 2593 ] ]
 ]

需要一个php脚本。

1 个答案:

答案 0 :(得分:0)

$rule = "({2606} OR {2549} OR {2543} OR ({2605} AND {2562})) AND ({2387} OR {2383} OR {1990} OR {2412} OR {2411} OR {2409} OR ({2408} AND {2593}))";
$previous_rule = '';

// Clean Curly Braces and Trim is there's a space.
$rule = trim( str_replace( array( "{", "}" ) , "", $rule ) );

echo "INPUT: " . $rule . "<br><br>";

foreach( range('a', 'z') as $letter ){

    $substituted_part = "(". substitution( $rule ) . ")";

    $$letter = $substituted_part;

    $rule = str_replace( $substituted_part, $letter, $rule );

    if( $previous_rule != $rule )
        $previous_rule = $rule;
    else
        break;

}

echo "<PRE>";
print_r( replaceOriginal($rule) );

function replaceOriginal( $rule ){

    if( preg_match("/[a-z]/i", $rule) ){

        if( strpos( $rule, "AND" ) !== false )
            $processed_rule = array( "AND" => explode(" AND ", $rule ) );

        else if( strpos( $rule, "OR" ) !== false )
            $processed_rule = array( "OR" => explode(" OR ", $rule ) );

        foreach( $processed_rule as $operator => $values ){

            $processed_rule[$operator] = process( $values );
        }

        return $processed_rule;

    }

}

function process( $values ){

    foreach( $values as $key => $value ){

        if( !empty( $GLOBALS[$value] ) ){

            $substituted_value = str_replace( array( "(", ")" ) , "", $GLOBALS[$value] );

            $values[$key] = replaceOriginal( $substituted_value );;

        }

    }

    return $values;
}

function substitution( $rule ){

    // Get anything thats wrapped in parentheses.
    if( preg_match_all('#\((([^()]+|(?R))*)\)#', $rule, $matches) ){

        foreach( $matches[1] as $value ){
            return substitution( $value );
        }

    }else{

        return $rule;
    }
}