我需要检查字符串是否有简单的方程式并显示结果。
示例:
$string = 'Hello world'; // not math
$string = '100 + 10?'; // Results should be 110
$string = 'What is 10 + 5'; // Results should be 15
$string = '1*1=?'; // Results should be 1
$string = 'what is one plus one'; // Results should be 2
字符串可以包含字母,数字和字符
我试过
$string = 'What is 10 + 5';
$test = preg_replace('/[^0-9,\-\+\*\/]/', "", $string); // 10+5
我不确定如何计算结果并检查字符串是否有数学
解决:我使用此代码
if(preg_match('/[0-9\-\+\*\/]/', $string)){
$test = preg_replace('/[^0-9,\-\+\*\/]/', "", $string);
if(preg_match('/(\d+)(?:\s*)([\+\-\*\/])(?:\s*)(\d+)/', $test, $matches) !== FALSE){
$operator = $matches[2];
switch($operator){
case '+':
$p = $matches[1] + $matches[3];
break;
case '-':
$p = $matches[1] - $matches[3];
break;
case '*':
$p = $matches[1] * $matches[3];
break;
case '/':
$p = $matches[1] / $matches[3];
break;
}
$test = $p;
}
$data['response'] = $test;
}
答案 0 :(得分:0)
除了最后一个字符串之外,它将处理所有字符串。
$mixed = "100 + 10?";
$letters=array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V','W', 'X', 'Y', 'Z','?','=');
$only_numbers=str_replace($letters, '', $mixed);
echo "$only_numbers <br>";
$only_numbers = eval('return '.$only_numbers.';');
echo "$only_numbers <br>";