K. B.
K. B.

Reputation: 1430

Split address street name house number and room number

I need split address: Main Str. 202-52 into street=Main Str. house No.=202 room No.=52 I tried to use this:

$data['address'] = "Main Str. 202-52";
$data['street'] = explode(" ", $data['address']);
$data['building'] = explode("-", $data['street'][0]);

It is working when street name one word. How split address where street name have several words. I tried $data['street'] = preg_split('/[0-9]/', $data['address']);But getting only street name...

Upvotes: 1

Views: 2886

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627034

You may use a regular expression like

/^(.*)\s(\d+)\W+(\d+)$/

if you need all up to the last whitespace into group 1, the next digits into Group 2 and the last digits into Group 3. \W+ matches 1+ chars other than word chars, so it matches - and more. If you have a - there, just use the hyphen instead of \W+.

See the regex demo and a PHP demo:

$s = "Main Str. 202-52";
if (preg_match('~^(.*)\s(\d+)\W+(\d+)$~', $s, $m)) {
    echo $m[1] . "\n"; // Main Str. 
    echo $m[2] . "\n"; // 202
    echo $m[3];        // 52
}

Pattern details:

  • ^ - start of string
  • (.*) - Group 1 capturing any 0+ chars other than line break chars as many as possible up to the last....
  • \s - whitespace, followed with...
  • (\d+) - Group 2: one or more digits
  • \W+ - 1+ non-word chars
  • (\d+) - Group 3: one or more digits
  • $ - end of string.

Also, note that in case the last part can be optional, wrap the \W+(\d+) with an optional capturing group (i.e. (?:...)?, (?:\W+(\d+))?).

Upvotes: 2

Related Questions