Jump to content

Extract HouseName/number and StreetName from Address Line 1


the182guy

Recommended Posts

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

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.