php 基于通配符的字符串比较

php string comparison based on wildcard

需要比较两个字符串以获得 PAIR,条件是只有第 5 个索引处的字符不同(忽略前 4 个字符)...在 mysql 中可以通过 INBXOLC800Y = INBX_LC800Y(使用 '_' 通配符)但是如何在 PHP 中执行此操作...这是我的代码,但我想可能有更智能的 and/or 最短路径???

$first_sku_full=  "INBXOLC800Y";
$first_sku_short= substr($first_sku_full, 5); // gives LC800Y

$second_sku_full= "INBXPLC800Y";
$second_sku_short= substr($second_sku_full, 5); // gives LC800Y

if ( $first_sku_short == $second_sku_short ) {
    // 6th character onward is matched now included 5th character  
    $first_sku_short= substr($first_sku_full, 4); 
    $second_sku_short= substr($second_sku_full, 4); 
    if ( $first_sku_short != $second_sku_short ) { 
        echo "first and second sku is a pair";     
    }else{
        echo "first and second sku is NOT a pair;
    } 
}

您可以通过不分配所有这些变量来缩短它,只需测试 if.

中的子字符串
if (substr($first_sku_full, 5) == substr($second_sku_full, 5)) {
    if ($first_sku_full[4] != $second_sku_full[4])
        echo "first and second sku are a pair";
    } else {
        echo "first and second sku are NOT a pair";
    }
}

我们使用AND进一步消除if..else

$first_sku_full=  "INBXOLC800Y";
$first_sku_short= substr($first_sku_full, 5); // gives LC800Y

$second_sku_full= "INBXPLC800Y";
$second_sku_short= substr($second_sku_full, 5); // gives LC800Y

if ($first_sku_short == $second_sku_short && $first_sku_full[4] != $second_sku_full[4]) {
    echo "first and second sku are a pair";
} else {
    echo "first and second sku are NOT a pair";
}