Просмотр поста

.
ДоХтор
# КоханийВолодимир (31.10.2017 / 17:06)
Всем ку. Очень интересный вопрос. Есть у меня таблица в которой есть условия по типу < 3 или == 1
А на стороне сереве надо обработать это условие, то есть записать условие в переменную и отработать е
Т.к. вариант с eval() не безопасен, то я бы сделал поиск оператора (больше/меньше и т.п.) с помощью регулярки, и уже на основе найденного оператора выполнял бы действие (сравнение/прибавление и т.п.)
Пример (+/-)
<?php

$count = 2;
//$condt = ' < 3';
$condt = '== 1';

var_dump(execute($count, $condt)); // bool(false) 


function operand($str) {
    return (int)preg_replace('~\D+~', '', $str);
}

function operation($str) {
    $operations = [
        '+'  => 1, '-'  => 2, '*'  => 3, '/'  => 4, '>'  => 5,
        '<' => 6, '==' => 7, '!=' => 8, '>='  => 9, '<=' => 10
    ];
    $op = preg_replace('~[\d\s]+~', '', $str);
    
    return isset($operations[$op]) ? $operations[$op] : 0;
}

function execute($count, $condt) {
    $operation = operation($condt);
    $operand = operand($condt);
    
    switch ($operation) {
        case 1:
            $result = $count + $operand;
            break;
        case 2:
            $result = $count - $operand;
            break;
        case 3:
            $result = $count * $operand;
            break;
        case 4:
            $result = $count / $operand;
            break;
        case 5:
            $result = $count > $operand;
            break;
        case 6:
            $result = $count < $operand;
            break;
        case 7:
            $result = $count == $operand;
            break;
        case 8:
            $result = $count != $operand;
            break;
        case 9:
            $result = $count >= $operand;
            break;
        case 10:
            $result = $count <= $operand;
            break;
        default:
            $result = null;
    }
    
    return $result;
}