首页 > 解决方案 > 从变量字符串构建 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
}

这可以在我的代码中实现吗?

标签: php

解决方案


构建动态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");

推荐阅读