如何解析表示布尔值的字符串
我正在构建一个带有私有成员函数的 PHP 类,该函数返回一个字符串值,例如:
'true && true || false'
到公共成员函数。 (这个字符串是一些正则表达式匹配和属性查找的结果。)我想做的是让 PHP 解析返回的逻辑,并让前面提到的公共函数返回解析逻辑的布尔结果是 true 还是 false。
我尝试了 eval(),但根本没有输出。我尝试对布尔返回进行类型转换...但是无法对运算符进行类型转换...呵呵有什么想法吗? (如果您需要更多信息,请告诉我。)
I'm building a PHP class with a private member function that returns a string value such as:
'true && true || false'
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.
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.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
刚刚偶然发现了这个问题,但由于对使用
eval
相当不安,我决定继续寻找更好的解决方案。我发现 PHP 的另一个奇妙用途
filter_var
< /a> 函数,当传入FILTER_VALIDATE_BOOLEAN
标志时 (其中有很多)。这个“一行”函数似乎在安全将字符串(或其他)对象转换为布尔值方面做得很好:
并且,进行了一些测试:
输出:
我还没有看起来足够深入,但这个解决方案可能依赖于某个地方的
eval
,但是我仍然倾向于使用那些普通的eval
,因为我假设 < code>filter_var 还将在通过eval
管道传输之前处理任何输入的清理。Just stumbled upon this question, but being fairly uneasy about using
eval
, I decided to keep looking for a better solution.What I discovered is yet another wonderful use for PHP's
filter_var
function, when passing in theFILTER_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:
And, a little testing:
Output:
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 plaineval
ing since I assume thatfilter_var
would also handle sanitizing any input before piping it througheval
.eval()
对此可以完美地工作,但请记住您必须告诉它返回一些内容。如果将任何用户输入直接放入
eval()
中,还要确保对其进行清理。eval()
will work perfectly fine for this, but remember you have to tell it to return something.Also make sure you sanitize any user inputs if putting them directly into an
eval()
.让我们假设 eval() 对于您的情况来说是一个好的/好的解决方案。
打印
bool(true)
Let's assume eval() is an ok/good solution in your case.
prints
bool(true)