= 0; $i-- ) { $suma += (int) $cuerpo[ $i ] * $serie; $serie = ( 7 === $serie ) ? 2 : $serie + 1; } $resto = 11 - ( $suma % 11 ); if ( 11 === $resto ) { return '0'; } if ( 10 === $resto ) { return 'K'; } return (string) $resto; } /** * Normaliza un RUT a `XXXXXXXX-X` (sin puntos) y lo valida. * Solo personas naturales (menos de 50.000.000), como pide la API. * * @param mixed $texto RUT escrito por la persona. * @return string|null El RUT normalizado, o null si no es válido. */ public static function normalizar( $texto ) { if ( ! is_string( $texto ) ) { return null; } $limpio = strtoupper( preg_replace( '/[\s.]/', '', $texto ) ); if ( false === strpos( $limpio, '-' ) && strlen( $limpio ) > 1 ) { $limpio = substr( $limpio, 0, -1 ) . '-' . substr( $limpio, -1 ); } if ( ! preg_match( '/^(\d{7,8})-([0-9K])$/', $limpio, $m ) ) { return null; } if ( (int) $m[1] >= 50000000 || (int) $m[1] < 1000000 ) { return null; } if ( self::digito_verificador( $m[1] ) !== $m[2] ) { return null; } return $m[1] . '-' . $m[2]; } /** * ¿Es uno de los RUT de prueba? * * @param string $rut RUT ya normalizado. * @return bool */ public static function es_de_prueba( $rut ) { return in_array( $rut, self::DE_PRUEBA, true ); } /** * RUT con puntos para mostrar en pantalla. * * @param string $rut RUT normalizado. * @return string */ public static function formatear( $rut ) { if ( ! preg_match( '/^(\d{7,8})-([0-9K])$/', (string) $rut, $m ) ) { return (string) $rut; } return number_format( (int) $m[1], 0, ',', '.' ) . '-' . $m[2]; } }