假设您有一些字符串,我应该如何转换它们以便能够在 PHP 中对它们使用逻辑运算?有可能吗?
例子:我要
"x=1"&&"x=0"
返回false
。
最佳答案
简介
我注意到你有两个 Logical Operator &&
和 Assignment Operator在字符串 =
中并且您要评估赋值在字符串中有一个逻辑运算符。说真的,我不知道你是怎么来到这里的,但这是非常错误的
,但出于教育目的,请标记
分割
"x=1" && "x=0" = False
^ ^ ^
| | |
| |
X == 1 | |
| |
AND |
|
X == 0
上面的表达式总是false
因为X
不能等于
0
和 1
同时
为了能够在 PHP
中进行这样的评估,您需要编写自己的函数,例如 logicalString
,您可以在其中使用类似 logicalString("x=1")
或 logicalString("x=0")
假设
$x = 1; // Imagine value of X
示例 1 &&
// Start Evaluation with &&
if (logicalString("x=1") && logicalString("x=0")) {
echo "&& - True\n";
} else {
echo "&& - False\n";
}
输出 1
&& - False
示例 2 - ||
// Start Evaluation with ||
if (logicalString("x=1") || logicalString("x=0")) {
echo "|| - True\n";
} else {
echo "|| - False\n";
}
输出 2
|| - True
使用的函数( Not to be used in production See Why )
function logicalString($str) {
parse_str($str, $v);
foreach ( $v as $k => $var ) {
if (! isset($GLOBALS[$k]) || $GLOBALS[$k] != $var)
return false;
}
return true;
}
关于php - 字符串之间的逻辑运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11310859/