PHP检查数组是否包含字符串的开头

时间:2014-02-12 09:54:13

标签: php

如何检查给定值的 start 是否与预定义值列表中的条目匹配?

$model_no1 = "KK71458";
$model_no2 = "IX41";

$models = array("KK61", "KK71", "KK81", "IX", "IJ");

在上面的示例代码中,两个值都应返回有效匹配。

3 个答案:

答案 0 :(得分:1)

试试这个:

$model_no1 = "KK71458";
    $models = array("KK61", "KK71", "KK81", "IX", "IJ");
    foreach($models as $key=> $mod){
        if($mod == substr($model_no1,0,strlen($mod))){ 
            echo "key: ".$key.' with value: '.$mod;
        }
    }

答案 1 :(得分:0)

$models = array("KK61", "KK71", "KK81", "IX", "IJ");

$g = function($search) use ($models) {
    return array_filter($models, function($string) use($search) {
        return substr($search, 0, strlen($string)) == $string;
    });
};

print_r($g->__invoke('KK71458'));
print_r($g->__invoke('IX41'));
print_r($g->__invoke('SPONGEBOB'));

答案 2 :(得分:0)

我建议您使用strpos()功能,而不是substr()strlen()的组合:

$model_no1 = 'KK71458';
$model_no2 = 'IX41';

$models = array('KK61', 'KK71', 'KK81', 'IX', 'IJ');
$result1 = check_model($model_no1, $models);
$result2 = check_model($model_no2, $models);

function check_model($model_no, array $models) {
    foreach ($models as $needle) {
        if (0 === strpos($model_no, $needle))
            return true;
    }

    return false;
}

我编写了简单的test,用于检查strpos()strstr()substr()+strlen()的字符串比较效果。结果如下:

Test name       Repeats         Result          Performance     
strpos          10000           0.167221 sec    +0.00%
strstr          10000           0.169299 sec    -1.24%
substr+strlen   10000           0.207363 sec    -24.01%

如您所见strpos()有最佳效果。