Do the math sum of a text variable? (E.g 5865/100 )

孤人 提交于 2019-12-10 14:39:52

问题


I have a variable that is...

$whatever = "5865/100";

This is a text variable.

I want it to calculate 5865/100 , so that I can add it to other numbers and do a calculation.

Number_format doesn't work, as it just returns "5,865". Whereas I want it to return 58.65

I could do...

$explode=explode("/",$whatever);
if(count($explode)=="2") {
    $whatever = $explode[0]/$explode[1];
}

But it seems rather messy. Is there a simpler way?


回答1:


Evaluate as PHP expression, but first check if it contains only digits and operators and space, and suppress any errors.

if (preg_match('/^[\d\+\-\/\*\s]+$/', $s)) {
  @eval('$result = ' . $s . ';');
}



回答2:


You can use the eval function to evaluate a string as code. However, you have to be careful as to where this code comes from because it will execute anything passed to it, not just simple math. If you knew your string contained a mathematical formula, you could do the following

$answer = 0;
$whatever = "5865/100";

eval ('$answer = ' . $whatever . ';');
print($answer);


来源:https://stackoverflow.com/questions/2213209/do-the-math-sum-of-a-text-variable-e-g-5865-100

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