귀하의 정규식 지금까지 한 자리 번호와 일치하지 않습니다.
그럼 여기이 정규식에서 살펴 보자 :
#(\d+)\s*([+/*-])\s*(\d+)#
#
을 :
(\d+)
구분 기호 : 그것을 숫자를 한 번 이상 일치하고 그룹.
\s*
: 하나 +
또는 -
또는 *
또는 /
한 시간과 그룹을 일치 그것을
\s*
: 공간을 일치 0 번 이상
(\d+)
: 0 번 이상
([+/*-])
공간을 일치 일치 한 번 이상 숫자를 입력 한 다음 그룹화하십시오.
#
: 구분
는 이제 여기에 몇 가지 PHP - 푸를 사용하자 함수는 내가 here 사용 :
$input = '2 +2
5*3
6 - 8';
$output = preg_replace_callback('#(\d+)\s*([+/*-])\s*(\d+)#', function($m){
return $m[1].' '.$m[2].' '.$m[3].' = '. mathOp($m[2], (int)$m[1], (int)$m[3]);
}, $input); // You need PHP 5.3+. Anonymous function is being used here !
echo $output;
function mathOp($operator, $n1, $n2){
if(!is_numeric($n1) || !is_numeric($n2)){
return 'Error: You must use numbers';
}
switch($operator){
case '+':
return($n1 + $n2);
case '-':
return($n1 - $n2);
case '*':
return($n1 * $n2);
case '/':
if($n2 == 0){
return 'Error: Division by zero';
}else{
return($n1/$n2);
}
default:
return 'Unknown Operator detected';
}
}
출력 :
2 + 2 = 4
5 * 3 = 15
6 - 8 = -2
조언 :
,691을음수, 괄호, 로그 및 cos/sin 함수가 복잡해 지므로 파서를 사용하는 것이 더 낫습니다.
Lex보다는 regexp 해킹 – Ven
[strtok] (http://php.net/manual/en/function.strtok.php)와 같은 것을 사용하는 것이 좋습니다. – raina77ow