时间:2021-07-01 10:21:17 帮助过:17人阅读
测试下不就知道了
$str='100>88';eval("\$a=".$str.";");var_dump($a);
$str='100>88';eval("\$a=".$str.";");var_dump($a);
function check($str)
{
//去除所有空格
$str = str_replace(' ', '', $str);
//检测字符串是否含有特殊字符,因为要用到eval函数,需要禁止执行非计算的操作
//只允许使用数字、小数点、加减乘除和求余,大于号,小于号,等号
if(!preg_match('/^[0-9.+*\/%<>=-]+$/', $str, $matches))
{
return false;
}
//按照<, >, <=, >=进行切割
$left = '';
$right = '';
$opt = '';
while($str)
{
if(!$left)
{
//获取算术式左边值
preg_match('/^[0-9.+*\/%-]+/', $str, $matches);
if(!is_array($matches) || !isset($matches[0]))
{
return false;
}
$left = $matches[0];
$str = substr($str, strlen($left));
}
//获取算术式操作符
preg_match('/^[<>]=?/', $str, $matches);
if(!is_array($matches) || !isset($matches[0]))
{
return false;
}
$opt = $matches[0];
$str = substr($str, strlen($opt));
//获取算术式右边值
preg_match('/^[0-9.+*\/%-]+/', $str, $matches);
if(!is_array($matches) || !isset($matches[0]))
{
return false;
}
$right = $matches[0];
$str = substr($str, strlen($right));
//算术式比较
eval('$result = ' . $left . $opt . $right . ';');
if(false === $result)
{
return false;
}
//将右边值赋值给下一次比较的左边值
$left = $right;
}
return true;
}
//举例
var_dump(check('0<99<100')); //true
var_dump(check('100 > 88')); //true
var_dump(check('10 < 22 < 3*8 < 5.6*5 < 100 - 30')); //true
var_dump( check('10 < 9.9999')); //false
var_dump(check('10 > 9 + 0.9999')); //true
var_dump(check('9 % 7 <= 2 <= 2')); //true
var_dump(check('1 > 1')); //false
var_dump(check('23<32<77')); //true
var_dump(check('1 <= 1 <= 1')); //true
var_dump(check('1 <= 1 < 1')); //false
var_dump(check('2 < 2.00000')); //false
忘记排版了,不知道有没有更简单的了
=-]+$/', $str, $matches)) { return false; } //按照<, >, <=, >=进行切割 $left = ''; $right = ''; $opt = ''; while($str) { if(!$left) { //获取算术式左边值 preg_match('/^[0-9.+*\/%-]+/', $str, $matches); if(!is_array($matches) || !isset($matches[0])) { return false; } $left = $matches[0]; $str = substr($str, strlen($left)); } //获取算术式操作符 preg_match('/^[<>]=?/', $str, $matches); if(!is_array($matches) || !isset($matches[0])) { return false; } $opt = $matches[0]; $str = substr($str, strlen($opt)); //获取算术式右边值 preg_match('/^[0-9.+*\/%-]+/', $str, $matches); if(!is_array($matches) || !isset($matches[0])) { return false; } $right = $matches[0]; $str = substr($str, strlen($right)); //算术式比较 eval('$result = ' . $left . $opt . $right . ';'); if(false === $result) { return false; } //将右边值赋值给下一次比较的左边值 $left = $right; } return true;}//举例var_dump(check('0<99<100')); //truevar_dump(check('100 > 88')); //truevar_dump(check('10 < 22 < 3*8 < 5.6*5 < 100 - 30')); //truevar_dump( check('10 < 9.9999')); //falsevar_dump(check('10 > 9 + 0.9999')); //truevar_dump(check('9 % 7 <= 2 <= 2')); //truevar_dump(check('1 > 1')); //falsevar_dump(check('23<32<77')); //truevar_dump(check('1 <= 1 <= 1')); //truevar_dump(check('1 <= 1 < 1')); //falsevar_dump(check('2 < 2.00000')); //false