Skip to content

Instantly share code, notes, and snippets.

@cagartner
Forked from KennedyTedesco/gist:6173723
Last active January 2, 2016 00:09
Show Gist options
  • Save cagartner/8221539 to your computer and use it in GitHub Desktop.
Save cagartner/8221539 to your computer and use it in GitHub Desktop.
Formatar telefones
<?php
/**
*
* Formata um número de telefone para o formato (11) 11111-1111
*
* @author Kennedy Tedesco
* @param string $numero
* @return string
*/
function formatarTelefone($numero) {
$numero = preg_replace('/^[+]\d{2}|[^\d]/', '', $numero);
return preg_filter('/^(\d{2})(\d{4,5})(\d{4})$/', '($1) $2-$3', $numero);
}
// Exemplos
echo formatarTelefone('31991268787'); // 9 Dígitos
echo formatarTelefone('31 99126 8787'); // 9 Dígitos
echo formatarTelefone('31 99126-8787'); // 9 Dígitos
echo formatarTelefone('31-99126-8787'); // 9 Dígitos
echo formatarTelefone('3191268787'); // 8 Dígitos
echo formatarTelefone('+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