如何在 PHP 中解析一串布尔逻辑
我正在构建一个带有私有成员函数的 PHP 类,该函数返回一个字符串值,例如:
I'm building a PHP class with a private member function that returns a string value such as:
'true && true || false'
到一个公共成员函数.(这个字符串是一些正则表达式匹配和属性查找的结果.)我想做的是让 PHP 解析返回的逻辑,并让前面提到的公共函数返回解析逻辑的布尔结果是真还是假.
to a public member function. (This string is the result of some regex matching and property lookups.) What I'd like to do is have PHP parse the returned logic and have the aforementioned public function return whether the boolean result of the parsed logic is true or false.
我尝试了 eval(),但我根本没有得到任何输出.我尝试对布尔返回进行类型转换...但是无法对运算符进行类型转换...呵呵有什么想法吗?(如果您需要更多信息,请告诉我.)
I tried eval(), but I get no output at all. I tried typecasting the boolean returns...but there's no way to typecast operators...hehe Any ideas? (Let me know if you need more information.)
推荐答案
偶然发现了这个问题,但是对使用 eval
感到相当不安,我决定继续寻找更好的解决方案.
Just stumbled upon this question, but being fairly uneasy about using eval
, I decided to keep looking for a better solution.
我发现 PHP 的 filter_var
函数,当传入 FILTER_VALIDATE_BOOLEAN
标志 (其中有很多).
What I discovered is yet another wonderful use for PHP's filter_var
function, when passing in the FILTER_VALIDATE_BOOLEAN
flag (of which there are many).
这个单行"函数似乎在安全地将字符串(或其他)对象转换为布尔值方面做得很好:
This "one line" function seems to do well at safely converting a string (or other) object to a boolean:
<?php
/**
* Uses PHP's `filter_var` to validate an object as boolean
* @param string $obj The object to validate
* @return boolean
*/
function parse_boolean($obj) {
return filter_var($obj, FILTER_VALIDATE_BOOLEAN);
}
还有一点测试:
/**
* Let's do some testing!
*/
$tests = array (
"yes",
"no",
"true",
"false",
"0",
"1"
);
foreach($tests as $test) {
$bool = parse_boolean($test);
echo "TESTED: ";
var_dump($test);
echo "GOT: ";
var_dump($bool);
echo "
";
}
输出:
/*
TESTED: string(3) "yes"
GOT: bool(true)
TESTED: string(2) "no"
GOT: bool(false)
TESTED: string(4) "true"
GOT: bool(true)
TESTED: string(5) "false"
GOT: bool(false)
TESTED: string(1) "0"
GOT: bool(false)
TESTED: string(1) "1"
GOT: bool(true)
*/
我看的不够深入,但这个解决方案可能在某个地方依赖于 eval
,但我仍然支持使用那些通过普通的 eval
ing 因为我假设 filter_var
在通过 eval
管道之前也会处理任何输入的清理.
I haven't looked deep enough, but it's possible that this solution relies on eval
down the line somewhere, however I'd still side with using those over plain eval
ing since I assume that filter_var
would also handle sanitizing any input before piping it through eval
.
相关文章