Last active
October 13, 2020 20:13
-
-
Save mariojrrc/dbd39fc810355c62323d922e42c65e42 to your computer and use it in GitHub Desktop.
Função para validação e extração de telefones (celular ou fixo) no Brasil. A expressão leva em conta o formato internacional/nacional, com ou sem o DDD, de telefones fixos e celulares. Adaptado de https://gist.github.com/boliveirasilva/c927811ff4a7d43a0e0c
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 | |
declare(strict_types=1); | |
/** | |
* A função abaixo demonstra o uso de uma expressão regular que identifica, de forma simples, telefones válidos no Brasil. | |
* Exemplos válidos: +55 (21) 98888-8888 / 9999-9999 / 21 98888-8888 / 5511988888888 / +55 (021) 98888-8888 / 021 99995-3333 | |
* | |
* @param string $phoneString | |
* @param bool $forceOnlyNumber Passar false caso não queira remover o traço "-" | |
* @return array|null ['ddi' => 'string', 'ddd' => string , 'number' => 'string'] | |
*/ | |
static function brazilianPhoneParser(string $phoneString, bool $forceOnlyNumber = true) : ?array | |
{ | |
$phoneString = preg_replace('/[()]/', '', $phoneString); | |
if (preg_match('/^(?:(?:\+|00)?(55)\s?)?(?:\(?([0-0]?[0-9]{1}[0-9]{1})\)?\s?)??(?:((?:9\d|[2-9])\d{3}\-?\d{4}))$/', $phoneString, $matches) === false) { | |
return null; | |
} | |
$ddi = $matches[1] ?? ''; | |
$ddd = preg_replace('/^0/', '', $matches[2] ?? ''); | |
$number = $matches[3] ?? ''; | |
if ($forceOnlyNumber === true) { | |
$number = preg_replace('/-/', '', $number); | |
} | |
return ['ddi' => $ddi, 'ddd' => $ddd , 'number' => $number]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment