我在POST中收到一个字符串。字符串包含一个要解决的操作,例如:"34*5/2"或"56-4*3"或"5+4+6"ecc…每次操作总是不同的我如何解决我在字符串中找到的操作?我不想使用eval函数
这就是你需要的,所有功劳都归功于http://www.website55.com/php-mysql/2010/04/how-to-calculate-strings-with-php.html
<?php
function calculate_string( $mathString ) {
$mathString = trim($mathString); // trim white spaces
$mathString = ereg_replace ('[^0-9'+-'*'/'(') ]', '', $mathString); // remove any non-numbers chars; exception for math operators
$compute = create_function("", "return (" . $mathString . ");" );
return 0 + $compute();
}
$string = "34*5/2";
echo calculate_string($string); // outputs 85
工作示例在这里
https://eval.in/379103