Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 311
mike Avatar asked Mar 16 '10 16:03

mike


People also ask

How Preg_match () and Preg_split () function works *?

How Preg_match () and Preg_split () function works *? preg_match – This function is used to match against a pattern in a string. It returns true if a match is found and false if no match is found. preg_split – This function is used to match against a pattern in a string and then splits the results into a numeric array.

How preg_ split() Function works?

The preg_split() function is an inbuilt function in PHP which is used to convert the given string into an array. The function splits the string into smaller strings or sub-strings of length which is specified by the user. If the limit is specified then small string or sub-strings up to limit return through an array.


Video Answer


1 Answers

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.

like image 142
Gumbo Avatar answered Sep 23 '22 14:09

Gumbo