Skip to content

Instantly share code, notes, and snippets.

@punchi
Forked from rbarrigav/validar_rut.php
Last active May 12, 2021 19:13
Show Gist options
  • Save punchi/3a5c44e7aa7ac0609ce9e53365572541 to your computer and use it in GitHub Desktop.
Save punchi/3a5c44e7aa7ac0609ce9e53365572541 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 = preg_replace('/[\.\-]/i', '', $rut);
$dv = substr($rut, -1);
$numero = substr($rut, 0, strlen($rut) - 1);
$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;
}
@soniparf
Copy link

soniparf commented Oct 4, 2018

Hola! alguna forma de validar correctamente solo si incluyen el guion? (para obligar el uso del guion), saludos!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment