-2

I have a string that I grab from my DB which has town and zipcode information in it. I want to extract the zipcodes (always 5 digits) from it and build a select statement from it (using PHP) as follows:

$townZip = 'Boston(02108, 02112, 02116), Chelsea (02150), Revere (02151)';

<select>
  <option value="">Please Select</option>
  <option value="02108">02108</option>
  <option value="02112">02112</option>
  <option value="02116">02116</option>
  <option value="02150">02150</option>
  <option value="02151">02151</option>
</select>

Please note that the string can have varying number of towns, zipcodes so that solution has to be flexible enough to accomodate this.

rogerb
  • 251
  • 1
  • 4
  • 11

1 Answers1

2

Try this:

<?php
    $townZip = 'Boston(02108, 02112, 02116), Chelsea (02150), Revere (02151)';

    $zips = explode(',',preg_replace('#[^,0-9]#', '', $townZip));

    echo '<select>';
    echo '<option value="">Please Select</option>';
    foreach($zips as $zip){
        echo '<option value="'. $zip.'">'. $zip.'</option>';
    }
    echo '</select>';
?>

The above code removes everything except numbers and comma, then explodes it with the comma which gives the zipcodes you need. Then loop through the array of zipcodes and create select.

[UPDATED]

It will look a bit messy but you can achieve town names with zipcodes with the following:

<?php
    $townZip = 'Boston(02108, 02112, 02116), Chelsea (02150), Revere (02151)';

    $zips = explode(',',preg_replace('#[^A-Za-z,0-9(]#', '', $townZip));

    echo '<select>';
    echo '<option value="">Please Select</option>';
    $prev = '';
    foreach($zips as $zip){
        $temp = explode('(',$zip);
        if(isset($temp[1])){
            $prev = $temp[0];
            $temp[0] = $temp[1];
        }   
        echo '<option value="'. $temp[0].'">'. $prev. '-' . $temp[0].'</option>';
    }
    echo '</select>';
?>
Think Different
  • 2,815
  • 1
  • 12
  • 18
  • Thanks @Think Different! This works great. Really appreciate it. Is there a way to tweak this to include the town name in the option e.g. – rogerb Nov 04 '14 at 16:23
  • Thanks again @Think Different. The solution with town names while involved works just as great. Appreciate it! – rogerb Nov 04 '14 at 16:35