# Grabbing city names and numbers from a CSV file

I've got information that is imported from a CSV file that my site grabs every day with PHP. I'm just learning RegEx so I'm able to do what I need to do but am looking to get more efficient with my coding.

Some of example of the kinds of strings that would come in would be:

15 SE NORFOLK
5 NNE OAKLAND
1 S LOS ANGELES
1 NW SACRAMENTO
BOSTON


It's basically numbers then directional letters then city name. Sometimes there aren't numbers and letters so I'm checking to see first and then just deleting them with preg_replace if there are (I just need the city name).

Here's the expression I have that works:

$location = preg_replace('/^[\d]+[\s]+[a-zA-z]+[\s]/', '',$string);


I know with regex there are a bunch of different ways to different things so I'm curious if there's a more efficient way to do what I'm doing.

Leave out the square brackets:

^\d+\s+[A-Z]+\s+


Square brackets are used for "character classes", like

[A-Z]


which matches exactly one letter out of the range A to Z.

\d already is a class: all the numbers.

• Ok great! Thanks. I'm just learning, every little bit helps. – MxmastaMills Aug 31 '13 at 21:33

Because you know that the City is always the last word of the line, you could always just look for that by doing something like :

$location = preg_replace('(\S*\s)*([a-zA-Z]+)(\s*$)', '\2', \$string);


group 1: any non whitespace(\S) followed by a whitespace(\s) 0 or more times. (in your case up to 2)

group2: any letter 1 or more times (the city name)

group3: any number of spaces followed by the end of the line

note: IDK anything about PHP, so the way you need to reference the group names may be slightly different