php - 从变量字符串构建 if 语句
问题描述
我想根据if(){}
变量中指定的信息创建一个语句。
我当前的代码从 foreach 循环创建字符串,我试图过滤掉我的代码中的 IP 地址,使其不被输入到我的数据库中。
创建字符串的代码:
//Set excluded IP's
$exclude = "10.1.1.0/24, 192.168.1.0/24";
//Convert excluded to ranges
$ranges = cidrToRange($exclude);
//Build IP address exclusion if statement
$statement = NULL;
foreach($ranges as $ip_ranges) {
$statement .= " !((".ip2long($ip_ranges['start'])." <= $ip_address) && ($ip_dst <= ".ip2long($ip_ranges['end']).")) AND ";
}
//Strip and at end
$statement = rtrim($statement, "AND ");
之后需要将该$ip_address
变量插入到 if 语句中(在脚本后面)
$statement
具有变量中指定值的此代码的输出将$exclude
输出:
!((167837952 <= $ip_address) && ($ip_address <= 167838207)) AND !((3232235776 <= $ip_address) && ($ip_address <= 3232236031))
我想在 if 语句中使用该字符串,因此最终结果应如下所示:
if(!((167837952 <= $ip_address) && ($ip_address <= 167838207)) AND !((3232235776 <= $ip_address) && ($ip_address <= 3232236031))) {
//Do this
}
这可以在我的代码中实现吗?
解决方案
构建动态if
语句是一回事,测试它是另一回事。一个简单的替代方法是只搜索列表并检查 IP 地址是否在该范围内。这会检查每个项目,一旦匹配,它将停止并$save
为假。
//Convert excluded to ranges
$ranges = cidrToRange($exclude);
// Check if IP is to be saved -
$save = true;
foreach ( $ranges as $ip_ranges) {
if ( $ip_ranges['start'] <= $ip_address && $ip_address <= $ip_ranges['end'] ) {
$save = false;
break;
}
}
这假设这$ip_address
也是一个长而不是一个字符串,比如......
$ip_address = ip2long("10.10.0.1");
推荐阅读
- python - cv2的libpng15的导入错误如何纠正?[解决]
- github-api - 如何通过rest api获取github用户相关问题数据?
- spring-boot - 使用 SpringBoot 的普罗米修斯
- mongodb - $sort 中的 Mongo 和索引问题
- react-native - react-native-video 不适用于 muted=true
- r - 如何根据行索引在数据帧上执行滞后/超前
- javascript - 根据数组中元素的数量反应渲染样式
- java - Android为库模块创建模板
- php - PayPal PHP SDK 抛出错误“找不到类”?
- node.js - 使用“npm start”时,什么会阻止我的 html 页面在计算引擎 vm 中显示