Cristian Gonzalez Cristian Gonzalez - 2 months ago 9
PHP Question

Regex to extract a word in front of numbers between spaces

Example I have this string "Shop 1, some street here Mooloolaba 4557 QLD Australia"

I want to detect the postal code and get what is in front of it, i'm trying this without any success

\s(.*?)\s(\d{4})
I only want to get Mooloolaba and 4557

Answer Source

You can use this regex:

(\S+)\s+(\d{4})\b

RegEx Demo

Regex Breakup:

  • (\S+) - Match and capture one or more non-white-space characters
  • \s+ - Match one or more white-space characters
  • (\d{4}) - Match and capture four digits
  • \b - assert a word boundary