问题
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