phpregexpreg-split

Split a string by more than one delimiter


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.


Solution

  • 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.