This piece of code is used to parse a street address. It will break the address up into its components. The reason one might want to do this is to use user input to find a street using a spatially-enabled database. Of course, users don't always enter their addresses perfectly. Fortunately, the street network databases I have been using store streetname components in separate fields. If you leave off the directional prefix or the type, for example, it is still possible to find the right street by presenting a list of possible matches to the user.
Anyway, the database queries are another function altogether. This is just the code to separate the parts of the address. The code is catered to the two test cities I'm working with right now - Seattle, where every street has a prefix of suffix, and Honolulu, where many house numbers have dashes in them, but could easily be translated to the quirks of other cities. The user is asked to at least provide a name and a number, and not to use apartment numbers.
Comments welcome.
Input: $address
Output: $number, $name, $prefix (optional), $suffix (optional), $type (optional)
//parse address
$parts_array = explode(" ", $address);
if (ctype_digit($parts_array[0])) { // the first piece of the address is a valid number
$number = $parts_array[0];
//echo $number;
} elseif (preg_match("/\d-\d/", $parts_array[0])){ // user has provided a number with a dash
$number = str_replace("-", "0", $parts_array[0]);
//echo "dash $number";
} else { // no number given
echo "This address does not seem to begin with a number";
exit;
}
$fixes = array("NW", "NE", "SW", "SE", "N", "S", "E", "W");
$types = array("ACRD", "ALY", "AVE", "BLVD", "BR", "CIR", "CRST", "CT", "DR", "FRWY", "HWY",
"KY", "LN", "LOOP", "PKWY", "PL", "PT", "RD", "ST", "TER", "TRL", "WALK", "WAY");
for ($i=1; $i < count($parts_array); $i++) {
$parts_array[$i] = strtoupper($parts_array[$i]);
if (ctype_isdigit($parts_array[$i])) {
echo "Error: the parser has detected numeral values in your address. If your house number contains more than one number, hyphenate it instead of using a space. If you are searching for a numbered street, use the ordinal value (23rd, 15th, etc).";
exit;
}
if (in_array($parts_array[$i], $fixes)) {
if ($i == 1) {
$prefix = $parts_array[$i];
} else {
$suffix = $parts_array[$i];
}
} elseif (in_array($parts_array[$i], $types)) {
$type = $parts_array[$i];
} else {
if (isset($name)) {
$name = $name . " " . $parts_array[$i];
} else {
$name = $parts_array[$i];
}
}
}
if (empty($name)) {
echo "This does not appear to be a valid address - no street name found.";
exit;
}