Skip to content

Instantly share code, notes, and snippets.

@swthate
Created March 16, 2017 19:29
Show Gist options
  • Save swthate/c5395cd9efd89b0ef275d87a709192aa to your computer and use it in GitHub Desktop.
Save swthate/c5395cd9efd89b0ef275d87a709192aa to your computer and use it in GitHub Desktop.
Parse Address
<?php
/**
* This bit of code takes an array of address blocks---with a newline break separating
* street address from city, state, and zip code---and formats each piece of the address
* block into an HTML table.
*
* With each address block split into a table, we can easily paste it into a CSV spreadsheet.
*
* We go from:
*
* "226 Public Square
* Greenfield IA 50849"
*
* To:
*
* ------------------------------------------------------
* | 226 Public Square | Greenfield | IA | 50849 |
* ------------------------------------------------------
*
**/
// An array of address blocks to parse.
$addresses = array(
"226 Public Square
Greenfield IA 50849",
"907 Main Street
Grinnell IA 50112",
"620 G Avenue
Grundy Center IA 50638"
);
// Start table
echo '<table>';
// Loop through each address block
foreach( $addresses as $item ){
// Use newline break to explode each address into an array with two items: line 1 and line 2.
$list = explode( "\n", $item );
// Assign first exploded line to street_address var.
$street_address = $list[0];
// Take second line, and ignore zip and state characters. Assign this to city var.
$city = substr( $list[1], 0, -8 );
// Start table row. Each address block gets its own row.
echo '<tr>';
// Street Address cell.
echo '<td>' . $street_address . '</td>';
// City cell.
echo '<td>' . $city . '</td>';
// State cell.
$state = substr( $item, -8,2 );
echo '<td>' . $state . '</td>';
// Zip Code cell.
$zip = substr( $item, -5 );
echo '<td>' . $zip . '</td>';
// Close table row.
echo '</tr>';
}
// After our loop through the addresses array completes, we close the table.
echo '</table>';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment