网络营销电子商务研究中心

网络营销电子商务研究中心 (https://www.0058.net/index.php)
-   代码交流 (https://www.0058.net/forumdisplay.php?f=16)
-   -   邮政编码 验证 (https://www.0058.net/showthread.php?t=2978)

car 2008-01-24 10:19 PM

邮政编码 验证
 
美国的邮政编码格式很简单,易于实现标准化和检验。其格式是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";

}

?>


All times are GMT +8. The time now is 02:01 AM.

Powered by vBulletin Version 3.8.7
Copyright ©2000 - 2026, Jelsoft Enterprises Ltd.