Home » Php » Extract some data from string php

Extract some data from string php

Posted by: admin February 25, 2020 Leave a comment


Quick question to easily cut a string. I know the substr but I can not use it in my case.

I have for example this thong: “1 rue Maryse Bastie 69500 BRON”
I’d like to say “Get all the end before the numbers” in this case “BRON” and get the numbers. I want the city and the postalcode in difference variable.

The API I’m using returns the complete address but I’d like to cut out to save the city and postal code in a different table.

I think this subject can help me : Extracting a zip code from an address string but not to get the city.

For exemple, if i have 1 rue Maryse Bastie 69500 BRON
I want $city = “BRON” and $pc = “69500”

If i have 13 rue Hohwald 67000 Strasbourg
I want $city = “Strasbourg” and $pc = “67000”


How to&Answers:

I give you a workaround, it should totally works, but maybe you will have to improve it :

$test = '1 rue Maryse Bastie 69500 BRON';
\preg_match('/\b\d{4,5}.+$/i', $test, $out);
$output = \explode(' ', \trim($out[0]), 2);
array(2) {
  string(5) "69500"
  string(4) "BRON"

In the code above we have used regex to find this way :

  • find digits (many characters –> 4 or 5 five for french zipcode)
  • find all characters next the zipcode until the end

Next we remove spaces at start and end, then we split into an array.


If you are getting your string in the same format as you mentioned in your question, you can break the string into an array and collect the last two elements as you required values.

Let me show you.

$myString = "1 rue Maryse Bastie 69500 BRON";
$breakUP = explode(" ", $myString);
$totalElement = count($breakUP);
$city = $breakUP[$totalElement - 1]; // Last element
$zip = $breakUP[$totalElement - 2]; // Second Last element

Hope this helps you 🙂