2017-08-17 86 views
0

我有一個輸入電話號碼489998723(由用戶填寫)。 並形成數據庫,會用率如下前綴的陣列檢查數組中是否包含php中的值

4899981 
4899 
4899988 
489998 
4899987 
48999 

我將如何進行精確匹配。 示例用戶輸入489998723比應該匹配4899987

在此先感謝。

+5

的可能的複製[檢查多個值存在PHP數組](https://stackoverflow.com/questions/15515560/check-multiple-values- exists-php-array) – Troyer

+0

使用array_search(mixed $ needle,array $ haystack [,bool $ strict = false]) –

+0

爲什麼要在電話號碼上進行鬆散匹配? – Andreas

回答

0

建議使用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); 
} 

Sandbox code

+0

謝謝A.Mikhailov它完美的工作。非常感謝你 –

相關問題