Skip to content

Instantly share code, notes, and snippets.

@rgarciaj
Forked from punchi/validar_rut.php
Last active January 29, 2018 20:28
Show Gist options
  • Save rgarciaj/7e0418478014183e8df469df487452b2 to your computer and use it in GitHub Desktop.
Save rgarciaj/7e0418478014183e8df469df487452b2 to your computer and use it in GitHub Desktop.
Validar Rut en php
<?php
/**
* Comprueba si el rut ingresado es valido
* @param string $rut RUT
* @return boolean
*/
public function valida_rut($rut)
{
if (!preg_match("/^[0-9.]+[-]?+[0-9kK]{1}/", $rut)) {
return false;
}
$rut = rut_limpio($rut);
$dv = rut_dv($rut);
$numero = rut_numero($rut);
$i = 2;
$suma = 0;
foreach (array_reverse(str_split($numero)) as $v) {
if ($i == 8)
$i = 2;
$suma += $v * $i;
++$i;
}
$dvr = 11 - ($suma % 11);
if ($dvr == 11)
$dvr = 0;
if ($dvr == 10)
$dvr = 'K';
if ($dvr == strtoupper($dv))
return true;
else
return false;
}
function rut_limpio($rut) {
$rut = preg_replace('/[\.\-]/i', '', $rut);
return $rut;
}
function rut_numero($rut) {
$rut = rut_limpio($rut);
$numero = substr($rut, 0, strlen($rut) - 1);
return $numero;
}
function rut_dv($rut) {
$rut = rut_limpio($rut);
$dv = substr($rut, -1);
return $dv;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment