社会保障号(SSN)
在美国,每个人都被分配一个“社会保障号(SSN)”,它在很多场合都成为核查身份的手段,因此经常是表单上的必填字段。它总是由3位数字开始,接是2位数字,接着又是4位数字。在显示这个号码时,三个部分之间通常以破折号分隔,但有时人们会忘记。
在检验时还可以使用更多的规则。这三个部分之中任意一个部分都不能全是0。目前,前三位数字(区号)不能比772大,因为那些数字还没有被分配。当然,在新的号码被分配之后,脚本就要做相应的修改。程序清单11.3.1展示了SSN标准化及检验例程。
程序清单11.3.1 社会保障号函数库
<?php
// A function that will accept US SSNs
// and standardize them to xxx-xx-xxxx format.
function standardize_ssn($ssn) {
// First, remove all non-digits from the string
$s = preg_replace('/[^0-9]/', '', $ssn);
// Now, break it into it's appropriate parts and insert dashes.
return substr($s, 0, 3) . '-' . substr($s, 3, 2) . '-' . substr($s, 5);
}
// A function to check for SSN validity, requires a standardized number
function validate_ssn($ssn) {
// First split the number into 3 parts:
$parts = explode('-', $ssn);
// If any part is all 0's - Invalid
foreach ($parts as $p) {
if ($p == 0) {
return false;
}
}
// If the first part is greater than 772 (May need updated in future)
if ($parts[0] > 772) {
return false;
}
// Finally, if the final part is not 4 characters, it is invalid
if (strlen($parts[2]) != 4) {
return false;
}
// Otherwise, we made it, it's valid.
return true;
}
// Standardize & validate some SSN:
$ssn = array('774 35 4688', '354-00-0103', '123456789', 'Hello');
foreach ($ssn as $num) {
$st = standardize_ssn($num);
$valid = validate_ssn($st);
$output = $valid ? 'Valid' : 'Invalid';
echo "<p>{$st} - {$output}</p>\n";
}
?>
如果需要,可以通过访问美国社会保障管理局站点(
http://ssa.gov/)来进一步严格地检查SSN的有效性,那里有...SN查询表。