PHP use string as operator

泄露秘密 提交于 2019-11-27 09:41:34

You can use eval() as suggested by @konforce, however the safest route would be something like:

$left = (int)$a;
$right = (int)$b;
$result = 0;
switch($char){

  case "*":
    $result = $left * $right;
    break;

 case "+";
   $result = $left + $right;
   break;
// etc

}

safest method is a switch construct:

function my_operator($a, $b, $char) {
    switch($char) {
        case '=': return $a = $b;
        case '*': return $a * $b;
        case '+': return $a + $b;
        etc...
    }
}

The easiest but most dangerous method is to use eval.

$c = eval("return $a $char $b;");

take a look at the eval() function. you will need to build a proper php command and run inside the eval() to extract out the result.

You can do with eval however I would not suggest using eval.

If there is case operator can by anything you should check what operator is before using

switch($char)
{
  case '*':
    $result= $a * $b;
    break;

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