如何确定字符串是否是PHP中的Mathematical语句? [英] How to determine if a string is a Mathematical statement in PHP?
本文介绍了如何确定字符串是否是PHP中的Mathematical语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个实例的字符串:
I have this string for an instance:
"2 + 2 - 2"
,并且在求值时应返回int(2)
;
"2 + 2 - 2"
and when evaluated it should return int(2)
;
我正在寻找一个函数/解析器,它可以确定字符串中是否匹配任何种类的数学内容.更多示例:
I'm looking for a function/parser witch can determine if anykind of math content is matched within a string. More examples:
"(2 + 2) / 2"
"(4 / 8) * 12"
"128 * 8"
如果语句是这种Math类型,则不需要计算和计算这些Math表达式,只需要一个函数即可确定(True/False
返回值).
Do not need to evaluate and calculate these Math expressions, just need a function witch will determine (True/False
return values), if the statement is of this Math kind.
使用正则表达式或其他东西可能吗?谢谢!
Is this possible with regex or something? Thanks!
推荐答案
See eval. For example, you can do this:
$result = INF;
try {
eval("$result=" + myMathExpression); // Evaluate here
} catch (Exception $e) {
}
if($result != INF) echo("Expression is a valid mathematical expression.");
请小心,因为任何PHP代码都将被评估!
这篇关于如何确定字符串是否是PHP中的Mathematical语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文