views:

183

answers:

1

Looking for some help!

I need to split a string at the last occurrence of a space...

e.g. "Great Neck NY" I need to split it so I have "Great Neck" and "NY"

I haven't had a problem using preg_split with basic stuff but I'm stumped trying to figure out how to tell it only to split at the last occurrence! Any help would be appreciated!

Mike

+4  A: 

You could use a lookahead assertion:

preg_split('/\s+(?=\S+$)/', $str)

Now the string will be split at \s+ (whitespace characters) only if (?=\S+$) would match from this point on. And \S+$ matches non-whitespace characters immediately at the end of the string.

Gumbo
+1 Nice one! Been looking for something like this myself for a long time too.
fireeyedboy