从字符串中获取数字,转换为int并进行比较以查看是否在两个数字的范围内

时间:2018-02-15 13:15:17

标签: php substr

我尝试使用substr函数从字符串中获取两个数字,然后使用$convert = $numbers+0;将它们转换为int我然后想看看这个数字是否在两个数字之间设置一个数组,如果是则返回true。有人可以帮我吗?

$kacodes = array(27, 28);
$postcodearea = "KA21";
$numbers = substr($postcodearea, 2, 2);
$convert = $numbers +0;

if(($kacodes[0] <= $convert) && ($convert <= $kacodes[1])) {
    return true;
}

抱歉模糊不清!

请详细了解我在下面尝试实现的目标。我发现它可以正常工作,如果我手动将字符串添加到函数中,但是当它添加到if / else语句时,它似乎跳到其他。如果这有道理?

function postcode_form() {
    echo "<form method='post' action=''>
        <input id='postcode' name='postcode' type='text'>
        <input type='submit' name='button'></button>
    </form>";
}

function is_valid_postcode( $postcode = '' )
{   

    $ep = array("AB", "BT", "GY", "HS", "IM", "IV", "JE", "PH", "KW");
    $postcode = strtoupper( $postcode );

    return in_array( $postcode , $ep );

}

function is_valid_postcode_area( $postcodearea )
{   
    $kacodes = array(27, 28);
    $pacodes = array(20, 80);
    $pocodes = array(30, 41);

    $postcodearea = strtoupper( $postcodearea );

    if(substr($postcodearea, 0, 2) === "KA") {

        $numbers = substr($postcodearea, 2, 2);
        $convert = $numbers +0;
        var_dump($convert);

        if( ($kacodes[0] <= $convert) && ($convert <= $kacodes[1]) )  {
            return true;
        }
        else {
            return false;
        }
    }

    else {  
        return false;
    }
}


// define the woocommerce_after_single_product_summary callback 
function action_woocommerce_after_single_product_summary( $evolve_woocommerce_after_single_product_summary, $int ) { 

    postcode_form();

    if( isset( $_POST['postcode'] ) ){

    // Remove unwanted spaces if they're there
    $postcode = trim( $_POST['postcode'] );

    // Extract only the first two characters
    $postcode = substr($postcode, 0, 2 );

    $postcodearea = substr($postcode, 0, 4);

    // Check if the submitted post code is valid
    if( is_valid_postcode( $postcode )){
        echo "Sorry we don't deliver to your postcode";
    }

    elseif(is_valid_postcode_area($postcodearea)) {
        echo "Sorry we don't deliver to your postcode"; 
    }

    else {
        echo "We deliver to your postcode";     
    }



}

}; 

1 个答案:

答案 0 :(得分:0)

我设法解决导致问题的原因。我在$postcode中使用的变量$postcodearea已经限制为两个字符!

之前

 $postcode = trim( $_POST['postcode'] );

    // Extract only the first two characters
    $postcode = substr($postcode, 0, 2 );

    $postcodearea = substr($postcode, 0, 4);

<强>后

        $postcoderaw = trim( $_POST['postcode'] );

        // Extract only the first two characters
        $postcode = substr($postcoderaw, 0, 2 );

        $postcodearea = substr($postcoderaw, 0, 4);