检查数组中是否包含php中的值
问题描述:
我有一个输入电话号码489998723(由用户填写)。 并形成数据库,会用率如下前缀的阵列检查数组中是否包含php中的值
4899981
4899
4899988
489998
4899987
48999
我将如何进行精确匹配。 示例用户输入489998723
比应该匹配4899987
。
在此先感谢。
答
建议使用str_pos:
$phone = 489998723;
$arr = [
4899981,
4899,
4899988,
489998,
4899987,
48999,
];
rsort($arr);
$result = false;
foreach ($arr as $value) {
// First match will be string of max length because of sorting
if (strpos(strval($phone), strval($value)) === 0) {
$result = $value;
break;
}
}
if ($result) {
print_r ('result: ' . $result . PHP_EOL);
} else {
print_r ('not found' . PHP_EOL);
}
+0
谢谢A.Mikhailov它完美的工作。非常感谢你 –
的可能的复制[检查多个值存在PHP数组](https://*.com/questions/15515560/check-multiple-values- exists-php-array) – Troyer
使用array_search(mixed $ needle,array $ haystack [,bool $ strict = false]) –
为什么要在电话号码上进行松散匹配? – Andreas