I need to check if the strings have simple equations and display the result.
Examples:
$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
the string can contain letters, numbers and characters
I have tried
$string = 'What is 10 + 5';
$test = preg_replace('/[^0-9,\-\+\*\/]/', "", $string); // 10+5
I'm not sure on how to calculate the result and to check whether the string does have math or not
Solved: I used this code
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;
}