Reputation: 9529
How to split a string like this with a regular expression?
Route de la Comba 32 1484 Aumont (FR)
Chemin de la Vignetta 1 1617 Remaufens (FR)
Route du Village 136 1609 Besencens (FR)
NB: Between 32 and 1484 there are 2 spaces (displayed as one space in this question)
Upvotes: 0
Views: 218
Reputation: 163287
If the format is always the same you could try using implode and explode with a double whitespace:
$str = "Route de la Comba 32 1484 Aumont (FR)";
$splitByDoubleSpace = explode(" ", $str);
$splitBySingleSpace = explode(" ", $splitByDoubleSpace[1]);
$city = implode(" ", array_slice($splitBySingleSpace, 1)); // Return the array except the first entry
echo sprintf(
'Address: %s<br>Postal code: %s<br>City: %s',
$splitByDoubleSpace[0],
$splitBySingleSpace[0],
implode(" ", array_slice($splitBySingleSpace, 1))
);
That would give you:
Address: Route de la Comba 32
Postal code: 1484
City: Aumont (FR)
Upvotes: 0
Reputation: 91385
How about:
preg_match('/^(.+?)\h{2}(\d{4,5})\h+(.+)$/', $inputString, $matches);
Explanation:
^ : beginning of line
(.+?) : group 1, 1 or more any character, not greedy, address
\h{2} : 2 horizontal spaces
(\d{4,5}) : group 2, 4 upto 5 digits, postal code
\h+ : 1 horizontal space
(.+) : group 3, 1 or more any character, city
$ : end of line
Upvotes: 1