Search code examples
phpregexpcre

PHP PCRE - get city from address


I need to get from a full address the last words it contains, after the postal code (which should always be in the same order).

An example of an address:

Av. Elias Garcia (em frente ao Restaurante Pote) Palhais 2815-233 Charneca da Caparica

I need to get this part:

Charneca da Caparica

which, as you can see, is the last words after the postal code:

2815-233

I need a PCRE expression to match this. Any suggestions?


Solution

  • Something like this should be able to do it.

    preg_match('/\d{4}-\d{3}\s+(.*)/', $subject, $match);
    echo $match[1];
    

    PS: I wouldn't try to parse this using reg exp because it won't be efficient, what if the user put the city before the zip code. If you are 100% sure of your data it should be fine.