Last active
January 21, 2021 04:51
-
-
Save shandanjay/5732044e90a7f3a6d2f34dab993b4c57 to your computer and use it in GitHub Desktop.
Sri Lanka Mobile number validation in PHP
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 | |
$a = '+94715753168'; | |
$b = '0715753168'; | |
$c = '715753168'; | |
$d = '0094715753168'; | |
$e = '094-71-5-753-168'; | |
is_lk_mobile($a); //true | |
is_lk_mobile($b); //true | |
is_lk_mobile($c); //true | |
is_lk_mobile($d); //true | |
is_lk_mobile($e); //true | |
function clean_num($num){ | |
$num=preg_replace('/[^0-9]/', '', $num); // remove non-numericals | |
$num=ltrim($num,'0'); //remove leading zeros | |
return $num; | |
} | |
function check_for_mobile($num){ | |
$mobile_phone_codes = ['70', '71', '72', '75', '76', '77', '78']; | |
if( in_array(substr($num, 0, 2), $mobile_phone_codes ) ){ | |
return true; | |
} | |
return false; | |
} | |
/** | |
* @returns bool | |
**/ | |
function is_lk_mobile($str){ | |
$cleaned = clean_num($str); | |
if(strlen($cleaned)<9) return false; | |
if(strlen($cleaned)==9){ | |
return check_for_mobile($cleaned); | |
}else { | |
$last9 = substr($cleaned, -9); | |
return check_for_mobile($last9) && str_replace($last9, '', $cleaned)=='94'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In line number 17, the
trim()
function will remove the ending '0's as well.e.g. 0715753160 > 71575316 and 0715000000 > 715
use
ltrim()
instead oftrim()