Guest User

Untitled

a guest
May 22nd, 2018
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.89 KB | None | 0 0
  1. <?php
  2.  
  3. function validaCNPJ($cnpj)
  4. {
  5. $cnpj = preg_replace('/[^0-9]/', '', (string) $cnpj);
  6. // Valida tamanho
  7. if (strlen($cnpj) != 14)
  8. return false;
  9.  
  10. // Verifica se foi informada uma sequência de digitos repetidos. Ex: 11111111111111
  11. if (preg_match('/(\d)\1{14}/', $cnpj)) {
  12. return false;
  13. }
  14.  
  15. // Valida primeiro dígito verificador
  16. for ($i = 0, $j = 5, $soma = 0; $i < 12; $i++)
  17. {
  18. $soma += $cnpj{$i} * $j;
  19. $j = ($j == 2) ? 9 : $j - 1;
  20. }
  21.  
  22. $resto = $soma % 11;
  23.  
  24. if ($cnpj{12} != ($resto < 2 ? 0 : 11 - $resto))
  25. return false;
  26.  
  27. // Valida segundo dígito verificador
  28. for ($i = 0, $j = 6, $soma = 0; $i < 13; $i++)
  29. {
  30. $soma += $cnpj{$i} * $j;
  31. $j = ($j == 2) ? 9 : $j - 1;
  32. }
  33.  
  34. $resto = $soma % 11;
  35.  
  36. return $cnpj{13} == ($resto < 2 ? 0 : 11 - $resto);
  37. }
  38.  
  39. var_dump(validar_cnpj('11.444.777/0001-61'));
Add Comment
Please, Sign In to add comment