Skip to content

Instantly share code, notes, and snippets.

@aldoanizio
Forked from davidalves1/formatar_cnpj_cpf.md
Created May 12, 2018 19:37
Show Gist options
  • Save aldoanizio/6e46c0cb1f74d6a8a200b0b18993d584 to your computer and use it in GitHub Desktop.
Save aldoanizio/6e46c0cb1f74d6a8a200b0b18993d584 to your computer and use it in GitHub Desktop.
Função para formatar CNPJ e CPF. A função é para PHP, mas pode ser utilizado no JS com pequenas modificações.
function formatarCnpj($cnpj_cpf)
{
  if (strlen(preg_replace("/\D/", '', $cnpj_cpf)) === 11) {
    $response = preg_replace("/(\d{3})(\d{3})(\d{3})(\d{2})/", "\$1.\$2.\$3-\$4", $cnpj_cpf);
  } else {
    $response = preg_replace("/(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})/", "\$1.\$2.\$3/\$4-\$5", $cnpj_cpf);
  }

  return $response;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment