1

I finally have a question that isn't already answered on Stack Overflow for PHP.

I need to save the city, state, zip in different variables. Given the string

$new = "PALM DESERT             SD63376        "

I am trying to strip spaces that are grouped in 2 or more so I can keep a city 2 words when it is supposed to be. Beyond that I can figure out but all my searching either shows how to split a string in a different language (Java), or how to split at one space which I cannot do.

I'm trying to use

$addr = preg_split('#^.*(?=\s{2, })#', $new);

but I am not getting the string split between PALM DESERT AND "SD63376       ". Please help!

jacoz
  • 3,508
  • 5
  • 26
  • 42
DitR
  • 123
  • 1
  • 10
  • What about one word cities? How are they going to be handled? Why is this in one string? Can you break it apart before it gets to this point? – Paul Dessert Jun 20 '13 at 22:45
  • http://stackoverflow.com/questions/559363/matching-a-space-in-regex This might help – Arth Du Jun 20 '13 at 22:45
  • unfortunately no, its what is passed into php from mysql. Its from an outside source – DitR Jun 20 '13 at 22:47
  • The Zerg are evolving regexes?!? Now we have more than two problems... – Jon Jun 20 '13 at 22:50
  • What about simply `preg_split('/\s{2,}/', $new)`? [It seems to work fine](http://ideone.com/M9vPTt). – Jon Jun 20 '13 at 22:52
  • I had tried that earlier but for some reason it didn't work, but then when I tried it after you suggested it, it decides to work :/ Thanks! – DitR Jun 20 '13 at 23:05

1 Answers1

2

You can use the following:

$str = "PALM DESERT             SD63376        ";
// note that there are two spaces in the regex pattern
var_dump(preg_split('~  +~', $str, -1,  PREG_SPLIT_NO_EMPTY));

Output:

array(2) {
  [0] =>
  string(11) "PALM DESERT"
  [1] =>
  string(7) "SD63376"
}
hek2mgl
  • 152,036
  • 28
  • 249
  • 266