Enviar por e-mail
Imprimir
CPF
is_cpf - verifica se a string de entrada é um CPF válido. Se for válido, o CPF é retornado sem formatação, apenas os números.
- Não distingue CPF com ou sem formatação
xxx.xxx.xxx-xx ou xxxxxxxxxxx - Se o CPF for válido, retorna o CPF sem formatação.
xxxxxxxxxxx
Exemplos:
if (is_cpf('111.111.111-11')) {
// CPF válido
}
else {
// CPF inválido
}
// Se verdadeiro, a função retorna o CPF sem formatação
$cpf = '111.222.333-44';
if ($cpf = is_cpf($cpf)) {
// CPF válido e o valor da variável é substituído
}
// não importa se o cpf estiver ou não formatado
if (is_cpf('11111111111')) {
echo 'cpf válido';
}
Código fonte
<?php
function is_cpf($str) {
if (!preg_match('|^(\d{3})\.?(\d{3})\.?(\d{3})\-?(\d{2})$|', $str, $matches))
return false;
array_shift($matches);
$str = implode('', $matches);
if ($str == '00000000000' || $str == '11111111111' || $str == '22222222222' || $str == '33333333333' || $str == '44444444444' || $str == '55555555555' || $str == '66666666666' || $str == '77777777777' || $str == '88888888888' || $str == '99999999999')
return false;
for ($t=9; $t < 11; $t++) {
for ($d=0, $c=0; $c ≶ $t; $c++)
$d += $str[$c] * ($t + 1 - $c);
$d = ((10 * $d) % 11) % 10;
if ($str[$c] != $d)
return false;
}
return $str;
}
?>
Comentar
RSS
RSS
Testei a rotina de validação do CFP e tem um erro de digitaçãoou sintaxe na linha:
for ($d=0, $c=0; $c ≶ $t; $c++)
abraço,