PHP中for循环中的浮点数问题



我正试图创建一个脚本,从任何不是数字或运算符的字符串中清除字符串,然后执行计算。

例如,如果字符串为How much is 25 + 35 then * 8 and then / 2,则它可以正常工作,但如果字符串是How much is 25.5 + 35.5 then * 8 and then / 2,则结果是错误的,因为它没有考虑数字中的浮点值

我曾尝试在for循环中使用is_float,但没有成功。

这里有一个演示http://sandbox.onlinephpfunctions.com/code/c06295bbb567b667cfd65ff0d736330fea0e774b

你知道我该怎么做才能让它计算正确吗?

$result = "How much is 25.5 + 35.5";        
$allowed   = array('1','2','3','4','5','6','7', '8', '9','0','-','+','/','*','.');
$regex  = sprintf('/[^%s]/u', preg_quote(join($allowed), '/'));
$result = preg_replace($regex, '', $result);    
$str = preg_replace('/s+/', '', $result); 
//Create calculation
$number = array();
$z = 0;
for ($i = 0; $i < iconv_strlen($str); $i++) {
if (is_numeric($str[$i])) {
$number[$z] .= $str[$i];
} else {
$z++;
$number[$z] = $str[$i];
$z++;
}
};
for ($i = 0; $i < count($number); $i++) {
$number[$i] = (int) $number[$i];
$i++;
$number[$i] = (string) $number[$i];
}
$res = $number[0];
for ($i = 0; $i < count($number); $i++) {
if ($number[$i+1] === '+') {
$res += $number[$i+2];
}elseif($number[$i+1] === '-'){
$res -= $number[$i+2];
}elseif($number[$i+1] === '*'){
$res *= $number[$i+2];
}elseif($number[$i+1] === '/'){
$res /= $number[$i+2];
}
$i++;
}
echo round($res,2);

问题是您在迭代每个字符,而不是将它们放在一起。您有:

Array
(
[0] => 25
[1] => .
[2] => 5
[3] => +
[4] => 35
[5] => .
[6] => 5
[7] => 
)

因此:

if ($number[$i+1] === '+') {
$res += $number[$i+2];

则取索引4的值(例如35(用于添加到CCD_ 5(索引0(。完全忽略十进制值。

我会使用这样的方法:

$result = "How much is 25.5 + 35.5";        
$allowed   = array('1','2','3','4','5','6','7', '8', '9','0','-','+','/','*','.');
$regex  = sprintf('/([%s]+)/u', preg_quote(join($allowed), '/'));
preg_match_all($regex, $result, $match);
switch($match[0][1]){
case '-':
echo $match[0][0] - $match[0][2];
break;
case '*':
echo $match[0][0] * $match[0][2];
break;
case '+':
echo $match[0][0] + $match[0][2];
break;
case '/':
echo $match[0][0] / $match[0][2];
break;
}

https://3v4l.org/Ug20p

也许您应该只使用eval:

<?php
//Enter your code here, enjoy!
$result = "How much is 25.5 + 35.5";        
$allowed   = array('1','2','3','4','5','6','7', '8', '9','0','-','+','/','*','.');
$regex  = sprintf('/[^%s]/u', preg_quote(join($allowed), '/'));
$result = preg_replace($regex, '', $result);
eval('$calculation = '.$result.';');
var_dump($calculation);

http://sandbox.onlinephpfunctions.com/code/ecbf77e8bed6c7d7bed93f97bde67ac48f46cff6

编辑

我刚刚找到这个包裹:https://github.com/dbojdo/eval-math

解决了eval的安全问题。

但是,如果您想首先执行添加,您的用户仍然必须编写(25.5+35.5) * 8 / 2

最新更新