Validar CPF em PHP (Completo)
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 | |
function validaCPF($cpf) { | |
// Extrai somente os números | |
$cpf = preg_replace( '/[^0-9]/is', '', $cpf ); | |
// Verifica se foi informado todos os digitos corretamente | |
if (strlen($cpf) != 11) { | |
return false; | |
} | |
// Verifica se foi informada uma sequência de digitos repetidos. Ex: 111.111.111-11 | |
if (preg_match('/(\d)\1{10}/', $cpf)) { | |
return false; | |
} | |
// Faz o calculo para validar o CPF | |
for ($t = 9; $t < 11; $t++) { | |
for ($d = 0, $c = 0; $c < $t; $c++) { | |
$d += $cpf[$c] * (($t + 1) - $c); | |
} | |
$d = ((10 * $d) % 11) % 10; | |
if ($cpf[$c] != $d) { | |
return false; | |
} | |
} | |
return true; | |
} |
eu faço assim
echo $cpf = formatar_cpf_cnpj('039.943.865-35');
function formatar_cpf_cnpj($doc) {
$doc = preg_replace("/[^0-9]/", "", $doc);
$qtd = strlen($doc);
if($qtd >= 11) {
if($qtd === 11 ) {
$docFormatado = substr($doc, 0, 3) . '.' .
substr($doc, 3, 3) . '.' .
substr($doc, 6, 3) . '.' .
substr($doc, 9, 2);
} else {
$docFormatado = substr($doc, 0, 2) . '.' .
substr($doc, 2, 3) . '.' .
substr($doc, 5, 3) . '/' .
substr($doc, 8, 4) . '-' .
substr($doc, -2);
}
return $docFormatado;
} else {
return 'Documento invalido';
}
}
@MauricioSarmento a ideia do script é verificar se o CPF é válido. E não apenas formatar.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Valew! Código top, usei em meu projeto LARAVEL e funcionou perfeitamente. Parabéns!!!!