Enviar por e-mail
Imprimir
Foto por Alan D
is_cnpj - verifica se a string de entrada é um CNPJ válido. Se for válido, o CNPJ é retornado com 14 caracteres e sem formatação.
- Não distingue CNPJ com ou sem formatação
xxx.xxx.xxx/xxxx-xx ou xxxxxxxxxxxxxxx - Não faz diferença se o CNPJ é composto por 14, 15, 18 ou 19 caracteres
xx.xxx.xxx/xxxx-xx, xxxxxxxxxxxxxx, xxx.xxx.xxx/xxxx-xx ou xxxxxxxxxxxxxxx - Se for válido, retorna o CNPJ com 14 caracteres e sem formatação
xxxxxxxxxxxxxx
Exemplos:
if (is_cnpj($cnpj)) {
// CNPJ válido
}
else {
// CNPJ inválido
}
// Se verdadeiro, a função retorna o CNPJ sem formatação e com 14 caracteres
$cnpj = '10.530.985/0001-10';
if ($cnpj = is_cnpj($cnpj)) { // atribuição e comparação
// CNPJ válido
echo $cnpj; // 10530985000110
}
// Erro comum de outros códigos, validar cadeia de zeros
if (is_cnpj('00.000.000/0000-00')) {
// ...
}
// CNPJ com 19 caracteres
if (is_cnpj('010.530.985/0001-10')) {
echo 'cnpj válido';
}
// CNPJ sem formatação
if (is_cnpj(10530985000110)) {
echo 'cnpj válido';
}Código fonte
<?php
/**
* Verifica CNPJ
*
* @author Alejandro Fernandez Moraga <moraga86@gmail.com>
* @link http://www.moraga.com.br
* @param string $str CNPJ
* @return string|false
*/
function is_cnpj($str) {
if (!preg_match('|^(\d{2,3})\.?(\d{3})\.?(\d{3})\/?(\d{4})\-?(\d{2})$|', $str, $matches))
return false;
array_shift($matches);
$str = implode('', $matches);
if (strlen($str) > 14)
$str = substr($str, 1);
$sum1 = 0;
$sum2 = 0;
$sum3 = 0;
$calc1 = 5;
$calc2 = 6;
for ($i=0; $i <= 12; $i++) {
$calc1 = ($calc1 < 2) ? 9 : $calc1;
$calc2 = ($calc2 < 2) ? 9 : $calc2;
if ($i <= 11)
$sum1 += $str[$i] * $calc1;
$sum2 += $str[$i] * $calc2;
$sum3 += $str[$i];
$calc1--;
$calc2--;
}
$sum1 %= 11;
$sum2 %= 11;
return ($sum3 && $str[12] == ($sum1 < 2 ? 0 : 11 - $sum1) && $str[13] == ($sum2 < 2 ? 0 : 11 - $sum2)) ? $str : false;
}
?>
Comentar
RSS
RSS