Skip to content

Instantly share code, notes, and snippets.

@Sleavely
Created July 18, 2013 07:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sleavely/6027308 to your computer and use it in GitHub Desktop.
Save Sleavely/6027308 to your computer and use it in GitHub Desktop.
<?php
function validatePNumber($pnumber) {
// reference: http://en.wikipedia.org/wiki/National_identification_number#Finland
//initial format thingy
$pnumber = strtoupper($pnumber);
if(!preg_match('/^([0-9]{6})(\-|\+|A)?([0-9]{3})([0-9A-Y])$/', $pnumber, $matches)) return false;
//loop through each character of $matches[1].$matches[3] and sum them up
$numstring = $matches[1].$matches[3];
$summed = 0;
for ($i = (strlen($numstring)-1), $j = 1; $i >= 0; $i--, $j *= 10)
{
$summed += intval($numstring[$i]) * $j;
}
//validation of checksum and stuff
$checkmarks = array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','H','J','K','L','M','N','P','R','S','T','U','V','W','X','Y');
$expected_checkmark = $checkmarks[$summed % 31];
if($expected_checkmark !== $matches[4]) return false;
//apparently the user did not fail, thus passing. logic is undeniable, yo
return true;
//some PNOs to test against:
$testpnos = array(
'311201A681K', //this one is supposed to fail
'280289-123J', //this one is supposed to fail
'870619-249K', //fail because its YYMMDD instead of DDMMYY
'170193121N',
'170193-121N',
'310560-2087',
'080170-0067',
'060973-077E',
'161249-102x',
'240556-118s',
'220691-167W',
'230892-079K',
'160873-2013',
'060690A089T',
'311068-104Y',
'250769+164V',
'231057-099T',
'290688-167M',
'080275080P',
'200585-1988',
'250686-131C',
'020770-1937',
'051287-093B',
'111090-195N',
'020689-0656',
'070185-2710',
'050182-0338',
'210966-1699',
'040589-185J',
'251189-1250',
'020465-283D',
'290892-149P',
'170192-0792',
'270676-118N',
'110685-045A',
'050576-2276',
'251248-506H',
'090491-2032',
'081091-148F',
'260282-2022',
'180371-173X',
'230684-157D',
'181287-2637',
'280770-141A',
'300580-1595',
'280469-1210',
'080992-2131',
'260987-0791',
'180488-075Y',
'081276-126H',
'010883-1168',
'150184-1267',
'270487-080N',
'040786-2117',
'020292-1106'
);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment