the182guy Posted September 21, 2009 Share Posted September 21, 2009 Hi all, I am trying to parse the house name or number, and the street name from an address line 1 string. Currently I am just using explode() on the first space but that is not accurate as you can imagine. Example strings for address line 1 would be things like: Unit 1-3 High St 101 London Rd Manor House, Royal Street Thanks in advance Link to comment https://forums.phpfreaks.com/topic/174990-extract-housenamenumber-and-streetname-from-address-line-1/ Share on other sites More sharing options...
thebadbad Posted September 21, 2009 Share Posted September 21, 2009 You could explode() on a comma, if any is found, else grab the number with a regular expression: <?php $addresses = array('Unit 1-3 High St', '101 London Rd', 'Manor House, Royal Street'); foreach ($addresses as $address) { if (strpos($address, ',') !== false) { list($number, $street) = explode(',', $address, 2); } else { preg_match('~^(.*?)((?:unit )?(?:[0-9]+\s?-\s?[0-9]+|[0-9]+))(.*)$~is', $address, $parts); $number = $parts[2]; if (trim($parts[3]) == '') { $street = $parts[1]; } else { $street = $parts[3]; } } echo "House number/name: $number; street name: $street<br />"; } ?> But this solution is far from foolproof, and it's impossible to make a perfect one, since we can't take every possible typing variant into account. We also assume the house name/number is entered first in a comma separated string. If the address is entered into a form, the best solution would be to have two fields; one for house number/name and one for street name. Link to comment https://forums.phpfreaks.com/topic/174990-extract-housenamenumber-and-streetname-from-address-line-1/#findComment-922339 Share on other sites More sharing options...
the182guy Posted September 21, 2009 Author Share Posted September 21, 2009 Thanks thebadbad, that helps Link to comment https://forums.phpfreaks.com/topic/174990-extract-housenamenumber-and-streetname-from-address-line-1/#findComment-922555 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.