Guest User

Untitled

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