我试图写一个正则表达式在PHP的if语句中使用,以检查是否包含至少1 +,-,*或/和至少2个数字的字符串。它们之间可以有任意数量的空格
最好的方法是什么?
我试着写一个正则表达式,下面,但这似乎不匹配我的测试用例。
我使用的正则表达式是:m/[0-9]{2,}[=-*/]+/
- 2 + 2 5 * 3
- 6 - 8
我的最终目标是在PHP中构建一个计算器,现在我正试图确定哪些输入是有效的数学输入/有效的数学表达式,哪些不是。
你的正则表达式不会匹配单个数字,因为你使用{2,}
,这意味着匹配字符2次或更多次。
我们来看看这个正则表达式:
#('d+)'s*([+/*-])'s*('d+)#
-
#
:分隔符 -
('d+)
:匹配一个数字一次或多次,然后将其分组。 -
's*
:匹配空格0次或多次 -
([+/*-])
:匹配+
或-
或*
或/
一次并将其分组 -
's*
:匹配空格0次或多次 -
('d+)
:匹配一个数字一次或多次,然后将其分组 -
#
:分隔符
让我们在这里使用一些PHP-Fu和我在这里使用的函数:
$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
建议:
这将变得相当复杂的负数,括号,对数和cos/sin函数,所以你最好使用解析器。
这将匹配您的测试。
/^
[0-9]+ # first number
's* # any whitespace
[+*'/-] # operand
's* # any whitespace
[0-9]+ # second number
$/x