Skip to content

Instantly share code, notes, and snippets.

@petrusnog
Created April 27, 2023 03:28
Show Gist options
  • Save petrusnog/cfb8475d0f279ccd2e4dec2d0fc111a4 to your computer and use it in GitHub Desktop.
Save petrusnog/cfb8475d0f279ccd2e4dec2d0fc111a4 to your computer and use it in GitHub Desktop.
Retrieves the phone structure from a given phone number.
<?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