Skip to content

Instantly share code, notes, and snippets.

@eyecatchup
Created January 16, 2014 08:07
Show Gist options
  • Save eyecatchup/8451373 to your computer and use it in GitHub Desktop.
Save eyecatchup/8451373 to your computer and use it in GitHub Desktop.
PHP function to get an array with indexes 'name' and 'num' from a string containing a street name and number.
<?php
/**
* Takes a string containing a (german) street name and number and
* returns an array with indexes 'name' (containing the street name)
* and 'num' (containing the street number). If no match is found,
* return value is boolean 'false'.
*/
function splitStreetNameNumber($str, $numRequired = false) {
$str = trim($str);
$tmp = @preg_split('/[0-9]+/', $str);
$num = trim(str_replace(trim($tmp[0]), '', $str));
if ( 0 >= strlen($str) || 0 >= strlen(trim($tmp[0])) || ($numRequired && 0 >= strlen($num)) ) {
return false;
}
return array(
'name' => trim($tmp[0]),
'num' => trim(str_replace(trim($tmp[0]), '', $str)),
);
}
// Examples:
$a = array(
'Karlstr. 2',
'12345',
'Karl Straße 2d',
'Karlsplatz 14 a',
'',
'Karlsplatz',
);
foreach($a as $b) {
$c = splitStreetNameNumber($b);
if (!$c) {
printf("Match result for '%s': Not a valid address.\r\n", $b);
}
else {
printf("Match result for '%s': Streetname: '%s', Streetnumber: '%s'.\r\n", $b, $c['name'], $c['num']);
}
/* Prints:
* Match result for 'Karlstr. 2': Streetname: 'Karlstr.', Streetnumber: '2'.
* Match result for '12345': Not a valid address.
* Match result for 'Karl Straße 2d': Streetname: 'Karl Straße', Streetnumber: '2d'.
* Match result for 'Karlsplatz 14 a': Streetname: 'Karlsplatz', Streetnumber: '14 a'.
* Match result for '': Not a valid address.
* Match result for 'Karlsplatz': Streetname: 'Karlsplatz', Streetnumber: ''.
*/
}
print "\r\n--------------------------------\r\n\r\n";
foreach($a as $b) {
$c = splitStreetNameNumber($b, true); // set 2nd parameter to 'true' in case a street number is required.
if (!$c) {
printf("Match result for '%s': Not a valid address.\r\n", $b);
}
else {
printf("Match result for '%s': Streetname: '%s', Streetnumber: '%s'.\r\n", $b, $c['name'], $c['num']);
}
/* Prints:
* Match result for 'Karlstr. 2': Streetname: 'Karlstr.', Streetnumber: '2'.
* Match result for '12345': Not a valid address.
* Match result for 'Karl Straße 2d': Streetname: 'Karl Straße', Streetnumber: '2d'.
* Match result for 'Karlsplatz 14 a': Streetname: 'Karlsplatz', Streetnumber: '14 a'.
* Match result for '': Not a valid address.
* Match result for 'Karlsplatz': Not a valid address.
*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment