Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Regex for getting directions in an address

Tags:

regex

php

I have this sample address:

405 W 1st Street South west #910

And I have this regex expression to extract the possibilities of an address that has the word North, South, West, East, North East, North West, South East, South West:

preg_match_all("/(?:(?:north|south)(?:[ ](?:east|west))?|east|west)/i", $address, $match);

Now if we look at the address string above, "W" is considered as West, so there could even be N, S, NW, NE, SE, SW, E, W. So we also need to extract these.

I'm not too good at regular expressions, hope you could help? Thanks!

like image 472
Knide Avatar asked Feb 03 '26 21:02

Knide


1 Answers

You can use

\b(?:north|south)(?:\h*(?:east|west))?\b|\b(?:east|west|[NS][WE]?|[EW])\b

See demo

Explanation:

  • \b - leading word boundary
  • (?:north|south) - either north or south
  • (?:\h*(?:east|west))? - one or zero occurrences of zero or more horizontal whitespaces (\h*) followed with either east or west
  • \b - trailing word boundary
  • | - or...
  • \b - leading word boundary
  • (?:east|west|[NS][WE]?|[EW]) - either east, west, N, NW, NE, S, SW, SE
  • \b - trailing word boundary
like image 143
Wiktor Stribiżew Avatar answered Feb 06 '26 11:02

Wiktor Stribiżew