![]() |
|
|||||||
| 代码交流 ASP,PHP,JSP等网站源代码下载与交流。 |
|
|
Thread Tools | Display Modes |
|
#1
IP: 222.76.215.18
|
|||
|
|||
|
美国的邮政编码格式很简单,易于实现标准化和检验。其格式是5个数字,后面还可能有一个破折号及4个数字。虽然这种格式很简单,但判断输入的邮政编码是否实际存在还是有一定困难的,基本方法就是查看当前有效编码列表,而这些列表必须从美国邮政局才能得到。因此,程序清单11.2.1里的邮政编码处理库只实现了格式标准化及检验。
程序清单11.2.1 邮政编码函数库 <?php // A function that will accept US zip codes // and standardize them to xxxxx-xxxx format. function standardize_zip($input) { // First, remove all non-digits from the string $digits = preg_replace('/[^0-9]/', '', $input); // Grab the first five digits: $ret = substr($digits, 0, 5); // If there are more than 5, then include the rest after a dash if (strlen($digits) > 5) { $ret .= '-' . substr($digits, 5); } return $ret; } // A function to check for zip code validity // It must have been standardized first. function validate_zip($input) { // First split the number into 2 parts: $parts = explode('-', $input); // If the first part is not 5 digits - Invalid if (strlen($parts[0]) != 5) { return false; } // If the second part exists, and is not 4 digits - Invalid if (isset($parts[1]) && (strlen($parts[1]) != 4)) { return false; } // Otherwise, we made it, it's valid. return true; } // Standardize & validate some zips: $zips = array('21771', '7177', 'x234 56', '12345-6789', '1313122', '14142-77743', '21705-123', '2177-1234', '1-1', '7.42'); foreach ($zips as $num) { $st = standardize_zip($num); $valid = validate_zip($st); $output = $valid ? 'Valid' : 'Invalid'; echo "<p>{$st} - {$output}</p>\n"; } ?> |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
|
|
Similar Threads
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| google电话验证成功的关键 | car | Google Adsense | 0 | 2007-12-16 05:44 PM |
| 用session代替apache服务器验证 | smiling | 代码交流 | 0 | 2006-12-15 07:25 PM |