Skip to content

Instantly share code, notes, and snippets.

@shandanjay
Last active January 21, 2021 04:51
Show Gist options
  • Save shandanjay/5732044e90a7f3a6d2f34dab993b4c57 to your computer and use it in GitHub Desktop.
Save shandanjay/5732044e90a7f3a6d2f34dab993b4c57 to your computer and use it in GitHub Desktop.
Sri Lanka Mobile number validation in PHP
<?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';
}
}
@ijasxyz
Copy link

ijasxyz commented Jan 20, 2021

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 of trim()

@shandanjay
Copy link
Author

shandanjay commented Jan 21, 2021

changed trim() to ltrim()
@ijasxyz Thanks !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment