Created
April 27, 2023 03:28
-
-
Save petrusnog/cfb8475d0f279ccd2e4dec2d0fc111a4 to your computer and use it in GitHub Desktop.
Retrieves the phone structure from a given phone number.
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 | |
/** | |
* @param string $phone_number | |
* @return string | |
*/ | |
function formatBrazilianPhone($phone_number) | |
{ | |
$phone_number = preg_replace( '/[^0-9]/', '', $phone_number ); | |
$phone_object = [ | |
'ddi' => '55', | |
'ddd' => null, | |
'number' => null | |
]; | |
switch (strlen($phone_number)) { | |
case 13: # (13 dígitos) CASO DDI + DDD + 9 + TELEFONE (13 Dígitos) | |
$phone_object['ddd'] = substr($phone_number, 2, 2); | |
$phone_object['number'] = substr($phone_number, 5); | |
break; | |
case 12: # (12 dígitos) CASO DDI + DDD + TELEFONE | |
$phone_object['ddd'] = substr($phone_number, 2, 2); | |
$phone_object['number'] = substr($phone_number, 4); | |
break; | |
case 11: # (11 dígitos) CASO DDD + 9 + TELEFONE | |
case 10: # (10 dígitos) CASO DDD + TELEFONE | |
$phone_object['ddd'] = substr($phone_number, 0, 2); | |
$phone_object['number'] = substr($phone_number, 2); | |
break; | |
default: | |
break; | |
} | |
return $phone_object; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment