最好的事情是爲你的建議「消毒液」,使用token_get_all
下面
(不完全)段,這樣以來EVAL結構是很危險的,你應該嘗試注入你可能會得到的想法
function evalExpression ($expression)
{
$code = "return $expression;";
$token = token_get_all($code,TOKEN_PARSE);
# return
unset($token[1]);
foreach ($token as $key=>$value) {
if(is_array($value)) {
# white list token
$allow = [T_WHITESPACE,T_LNUMBER,/* add more token*/];
# remove white list token
if(in_array($value[0],$allow,true)) {
unset($token[$key]);
}
} else {
# white list string
$allow = [';','>'/* add more element*/];
# remove white list string
if(in_array($value,$allow,true)) {
unset($token[$key]);
}
}
}
# if token contain only white listed, $token should empty
if(!$token) {
return eval($code);
} else {
throw new \InvalidArgumentException('err');
}
};
# return bool
var_dump(evalExpression('2 > 1'));
# should error
var_dump(evalExpression('function(){}'));
/使用惡意代碼進行測試,然後投入生產
否.............. –
我不會使用regexp來嘗試清理數據以進行計算;我會考慮編寫一個計算器,也許基於[this](http://stackoverflow.com/questions/12692727/how-to-make-a-calculator-in-php) –
Mark的建議非常好。否則,你可以構建一個遞歸解析器([這裏是一個很好的例子])(http://stackoverflow.com/questions/35426793/parsing-a-string-with-recursive-parentheses)) –