1

i have some strings (address), all like this:

2 rue lambda, 75018, PARIS

I want to get the postal code, in this exemple "75018". I've been trying different solution, but i'm not familiar with escaped characters , and don't know how to detect coma in the string. Which function should i use to extract the postal code?

4 Answers 4

3

you can try this:

preg_match('/([0-9]{5})/',$string,$match);
echo $match[1];

This will work whenever there is an address comma separated or simply space separated

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, this did it (with echo $match[0];), for my problem i think it's the best solution, beacause i'm sure the postal format will always be unique in the string(except for Corse departement whose postal code contain letters). The explode solution could cause problems if someone write he's address like "2, rue lambda...". Thanks everybody
@joey: yes this will work with any formattation. Please consider to mark this as the answer if this helped you.
Will probably break on "12345 Whatever, 23456, Fake City". Make sure your addresses will never have 5-or-more-digit numbers in them.
3

If the commas are always there, it is as simple as explode()

$parts = explode(",", "2 rue lambda, 75018, PARIS");
$postcode = trim($parts[1]);

1 Comment

what if there isn't the comma always there?
3

If all your addresses are of France, which has a 5 digit postal code then you can use the following regex to capture it:

\b(\d{5})\b

In PHP you can use it with preg_match as:

$input = '2 rue lambda, 75018, PARIS';
if(preg_match('/\b(\d{5})\b/',$input,$match)) {
   $postal_code = $match[1];
}

Note that this will capture the first 5 digit number in the address. Generally the postal code comes at the end of the address, so we can improve the method by capturing the last 5 digit number in the address by using the regex:

.*\b(\d{5})\b

Comments

0

Is that always the format it will be in? If so you can explode.

$str = '2 rue lambda, 75018, PARIS';
$array = explode(',',$str);
$street = $array[0];
$postal = $array[1];
$city = $array[2];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.