11c03-1.php
来自「介绍PHP5的给类型函数应用」· PHP 代码 · 共 46 行
PHP
46 行
<?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 numberfunction 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";}?>
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?