mike
mike

Reputation: 8141

php preg_split last occurrence of character

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

Upvotes: 5

Views: 3438

Answers (1)

Gumbo
Gumbo

Reputation: 655745

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.

Upvotes: 14

Related Questions