Skip to content

Instantly share code, notes, and snippets.

@tubalmartin
Created December 20, 2012 14:17
Show Gist options
  • Save tubalmartin/4345529 to your computer and use it in GitHub Desktop.
Save tubalmartin/4345529 to your computer and use it in GitHub Desktop.
Validación NIF de personas jurídicas y entidades en general (ESPAÑA)
<?php
/**
* Valida NIF de personas jurídicas y entidades en general
*
* @param string $nif NIF to check
*
* @return bool returns true on success false otherwise
*/
function nifEntity($nif)
{
$nif = strtoupper(str_replace("-", "", trim($nif)));
if (preg_match("/^[ABCDEFGHJNPQRSUVW]{1}[0-9]{7}[0-9A-Z]{1}/", $nif))
{
$nif_codes = 'JABCDEFGHI';
$sum = (string) getNifSum($nif);
$n = (10 - substr($sum, -1)) % 10;
if (strpos('ABCDEFGHJUV', $nif[0]) !== FALSE)
{
// Numerico
return ($nif[8] == $n);
}
else if (strpos('PQRSNW', $nif[0]) !== FALSE)
{
// Letras
return ($nif[8] == $nif_codes[$n]);
}
}
return FALSE;
}
// Función auxiliar usada para CIFs y NIFs especiales
function getNifSum($nif)
{
$sum = $nif[2] + $nif[4] + $nif[6];
for ($i = 1; $i < 8; $i += 2)
{
$tmp = (string) (2 * $nif[$i]);
$tmp = $tmp[0] + ((strlen($tmp) > 1) ? $tmp[1] : 0);
$sum += $tmp;
}
return $sum;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment