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