Last active
January 18, 2021 17:40
-
-
Save oRastor/e1490fcfd4e66508001e to your computer and use it in GitHub Desktop.
Simple and fast php function to compare two phone numbers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function isEqualPhoneNumber($phoneA, $phoneB, $substringMinLength = 7) | |
{ | |
if ($phoneA == $phoneB) { | |
return true; | |
} | |
// remove "0", "+" from the beginning of the numbers | |
if ($phoneA[0] == '0' || $phoneB[0] == '0' || | |
$phoneA[0] == '+' || $phoneB[0] == '+') { | |
return isEqualPhoneNumber(ltrim($phoneA, '0+'), ltrim($phoneB, '0+')); | |
} | |
// change numbers if second is longer | |
if (strlen($phoneA) < strlen($phoneB)) { | |
return isEqualPhoneNumber($phoneB, $phoneA); | |
} | |
if (strlen($phoneB) < $substringMinLength) { | |
return false; | |
} | |
// is second number a first number ending | |
$position = strrpos($phoneA, $phoneB); | |
if ($position !== false && ($position + strlen($phoneB) === strlen($phoneA))) { | |
return true; | |
} | |
return false; | |
} | |
// tests | |
$tests = array( | |
array('+380441234567', '+380441234567', true), | |
array('*111#', '*111#', true), | |
array('923001122333', '03001122333', true), | |
array('+380951000000', '380951000000', true), | |
array('0951000000', '0961000000', false), | |
array('0951033333', '33333', false), | |
array('+380951002030', '00380951002030', true), | |
array('0951002030', '095100203', false), | |
array('011380951002030', '+380951002030', true) | |
); | |
$passed = 0; | |
foreach ($tests as $testRecord) { | |
echo $testRecord[0] . ' AND ' . $testRecord[1] . PHP_EOL; | |
$result = isEqualPhoneNumber($testRecord[0], $testRecord[1]); | |
if ($result) { | |
echo 'Equal' . PHP_EOL; | |
} else { | |
echo 'Not Equal' . PHP_EOL; | |
} | |
if ($result == $testRecord[2]) { | |
$passed++; | |
echo '+++' . PHP_EOL; | |
} else { | |
echo '---' . PHP_EOL; | |
} | |
echo PHP_EOL; | |
} | |
echo $passed . ' of ' . count($tests) . ' Passed' . PHP_EOL; |
Hi,
I liked it, and it worked for my use case.
Nice and simple to begin with.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Test result output: