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

3
需要比较两个字符串,以获取仅在第5个索引处有不同字符的PAIR(忽略前4个字符)... 在MySQL中,可以通过INBXOLC800Y = INBX_LC800Y(使用'_'通配符)实现,但如何在PHP中实现... 这是我目前的代码,但我想可能有更聪明和/或更短的方法?
$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;
    } 
}

1
你从来没有检查过前4个字符。 - Barmar
@Barmar 是的,我忘记添加第一个4个字符不需要检查的内容了... - mhk
2个回答

0

您可以通过不分配所有这些变量来缩短它,只需在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";
    }
}

0

我们使用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";
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接