Saturday 15 January 2011

Extract zipcodes from string and build a select statement in php -



Extract zipcodes from string and build a select statement in php -

i have string grab db has town , zipcode info in it. want extract zipcodes (always 5 digits) , build select statement (using php) 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 string can have varying number of towns, zipcodes solution has flexible plenty accomodate this.

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 $zip){ echo '<option value="'. $zip.'">'. $zip.'</option>'; } echo '</select>'; ?>

the above code removes except numbers , comma, explodes comma gives zipcodes need. loop through array of zipcodes , create select.

[updated]

it bit messy can accomplish town names zipcodes 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 $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>'; ?>

php string text-extraction

No comments:

Post a Comment