Skip to content

Instantly share code, notes, and snippets.

@devrkd
Created June 1, 2021 08:05
Show Gist options
  • Save devrkd/0beed85dac6cc8f251eaadd4be17134e to your computer and use it in GitHub Desktop.
Save devrkd/0beed85dac6cc8f251eaadd4be17134e to your computer and use it in GitHub Desktop.
Split house number and extra info from street name using Laravel Str macro
<?php
Str::macro('addressSplitter', function (string $address) {
$leadingHouseNumber = '/^([\d-]+[a-z]{0,1}[\d-]?[\d,]?)\ ([a-z\ ]+)$/mi';
$endingWithHouseNumber = '/^([a-z\ ]+)([\d?]+)([\D+?]+[\d+?]?.+)?|([\D+?]+[\d+?]?+)$/mi';
if (preg_match_all($leadingHouseNumber, $address, $matches, PREG_SET_ORDER, 0)
&& isset($matches[0][1], $matches[0][2])
) {
$result['house_number'] = (int) $matches[0][1];
$result['street_name'] = trim($matches[0][2]);
$result['house_number_extra'] = '';
} elseif (
preg_match_all($endingWithHouseNumber, $address, $matches, PREG_SET_ORDER, 0)
&& isset($matches[0][1], $matches[0][2])
) {
$result['street_name'] = ! empty($matches[0][1]) ? $matches[0][1] : $matches[0][0];
$result['house_number'] = ! empty($matches[0][2]) ? (int) $matches[0][2] : '';
$result['house_number_extra'] = $matches[0][3] ?? $matches[1][0] ?? '';
} else {
$result['street_name'] = $address;
$result['house_number'] = '';
$result['house_number_extra'] = '';
}
return array_map('trim', $result);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment