PHP preg_match 使用正则表达式的简单数学表达式

PHP preg_match simple mathematical expression using regex

我想确保输入有效以进行简单计算。因此,我只想让字符匹配这些

0 to 9, + - * / ( )

所以我有 ~[^0-9()+\-*/]~ 作为我的正则表达式。 It works fine here

所以我在 PHP 中有这段代码。

$exp = (1+2*3)+4;
if(preg_match('~[^0-9()+\-*/]~', $exp)){
  eval("echo $exp;");
} else {
  echo "Bad Expression!";
}

这给了我 "Bad Expression!"

我做错了什么?

使用以下regex。您还需要转义除号 (/)。

$exp = (1+2*3)+4;
if(preg_match('~^[0-9()+\-*\/]+$~', $exp)){
  eval("echo $exp;");
} else {
   echo "Bad Expression!";
}

Demo Here