0

I am having the input string of

Aspen,Colorado-USA

I want to split it by using preg-split

I want this output:

Array ( [0] => Aspen [1] => Colorado [2] => USA )

I have used like this

$input=Aspen,Colorado-USA;
$out=preg_split( "%[^a-zA-Z\s]%",$input);

is it correct? I want to know efficient way to do this.

  • 4
    Even regex is not clever enough to modify the content. Do you mean you want the output `Array ( [0] => Aspen [1] => Colorado [2] => USA )`? – DaveRandom Jul 16 '12 at 11:32
  • Also, I assume `$input` is in fact a string? – Tim Pietzcker Jul 16 '12 at 11:35
  • Is the input data always in the form `City`,`State`-`Country`? Do you need to support *any* country, or do you have a specific list? And are there any other locations that need to be converted to Las Vegas, or is it only Aspen Colorado? – ghoti Jul 16 '12 at 11:41

1 Answers1

3

Assuming you don't want to turn Aspen into Las Vegas, you might want to split on , and -:

$out= preg_split('/[,-]/', $input);

However, this assumes that neither commas nor dashes will occur in your city/state names.

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
  • If there is a chance, that there might be dashes in state-city name, you can always make a DB with all possible states and city names ( probably downloadable from internet ) and check on those names when splitting. – Peon Jul 16 '12 at 11:36
  • 1
    ...or create a rule, for example to only split on the last dash in the string. But then again, you would fail for strings like `"Sarajevo, Sarajevski Kanton-Bosnia-Herzegovina"`... – Tim Pietzcker Jul 16 '12 at 11:39