Created
August 1, 2022 05:19
-
-
Save jvarn/df206c8b6df1b014abf67e9a6de06499 to your computer and use it in GitHub Desktop.
PHP function to make mobile numbers in full international format
This file contains hidden or 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 | |
/** | |
* Formats mobile numbers as international. | |
* | |
* @access public | |
* @param string $number is a mobile phone number | |
* @param array $args is an associative array of variables (see $defaults) | |
* @return string | |
*/ | |
function format_mobile_as_international( $number, $args=null ) { | |
$defaults = array( | |
'Country Code' => '966', // (966) 555555555 | |
'Local Prefix' => '0', // (0) 555555555 | |
'First Digit' => '5', // 0 (5) 55555555 | |
'IDD' => '00', // (00) 966 555555555 | |
'Local Length' => 10 // length as dialled locally e.g. 0555555555 = 10 digits | |
); | |
$args = array_merge( $defaults, (array) $args ); | |
// only keep digits: no spaces, dashes, plus signs, etc. | |
$number = preg_replace( "/[^0-9]/", "", $number ); | |
// Phone number is like 0555555555 | |
if ( $number[0] == $args['Local Prefix'] && strlen( $number ) == (int) $args['Local Length'] ) { | |
$number = substr( $number, strlen( $args['Local Prefix'] ) ); | |
$result = $args['Country Code'] . $number; | |
} | |
// Phone number is like 555555555 | |
elseif ( $number[0] == $args['First Digit'] && strlen( $number ) == (int) $args['Local Length'] - strlen( $args['First Digit'] ) ) { | |
$result = $args['Country Code'] . $number; | |
} | |
// Phone number is like 00966555555555 | |
elseif ( substr( $number, 0, strlen( $args['IDD'] ) ) == $args['IDD'] && strlen( $number ) == (int) $args['Local Length'] - strlen( $args['Local Prefix'] ) + strlen( $args['IDD'] ) + strlen( $args['Country Code'] ) ) { | |
$result = substr( $number, strlen( $args['IDD'] ) ); | |
} | |
// Phone number is like 966555555555 | |
elseif ( substr( $number, 0, strlen( $args['Country Code'] ) == $args['Country Code'] && strlen( $number ) == (int) $args['Local Length'] - strlen( $args['Local Prefix'] ) + strlen( $args['Country Code'] ) ) { | |
$result = $number; | |
} | |
// else omit | |
return $result; | |
} | |
echo format_mobile_as_international("00966555555555"); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment