Skip to content

Instantly share code, notes, and snippets.

@KennedyTedesco
Last active May 8, 2019 11:15
Show Gist options
  • Save KennedyTedesco/6173723 to your computer and use it in GitHub Desktop.
Save KennedyTedesco/6173723 to your computer and use it in GitHub Desktop.
Formatar número de telefone para o formato (11) 11111-1111
<?php
/**
*
* Formata um número de telefone para o formato (11) 11111-1111
*
* @author Kennedy Tedesco
* @param string $numero
* @return string
*/
function formatar_telefone($numero) {
$numero = preg_replace('/^[+]\d{2}|[^\d]/', '', $numero);
return preg_filter('/^(\d{2})(\d{4,5})(\d{4})$/', '($1) $2-$3', $numero);
}
// Exemplos
echo formatar_telefone('31991268787'); // 9 Dígitos
echo formatar_telefone('31 99126 8787'); // 9 Dígitos
echo formatar_telefone('31 99126-8787'); // 9 Dígitos
echo formatar_telefone('31-99126-8787'); // 9 Dígitos
echo formatar_telefone('3191268787'); // 8 Dígitos
echo formatar_telefone('+553191268787'); // 8 Dígitos
/*
(31) 99126-8787
(31) 99126-8787
(31) 99126-8787
(31) 99126-8787
(31) 9126-8787
(31) 9126-8787
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment