Question

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

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top