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

Get numbers from string, convert to int and compare to see if is within range of two numbers

我正在尝试使用 substr 函数从字符串中获取两个数字,然后使用 $convert = $numbers+0; 将它们转换为 int 然后我想看看这个数字是否在两个数字之间一个数组,如果是 return 则为真。谁能帮帮我吗?

$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 语句中时它似乎跳到 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";     
    }



}

}; 

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

之前

 $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);