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
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With