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"
例如“Great Neck NY”我需要分开它,所以我有“Great Neck”和“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!
我使用preg_split与基本的东西没有问题,但是我很难过,试图弄清楚如何告诉它只在最后一次出现时分裂!任何帮助,将不胜感激!
Mike
1 个解决方案
#1
12
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.
现在,只有当(?= \ S + $)从这一点开始匹配时,字符串才会被分割为\ s +(空白字符)。并且\ S + $会立即在字符串末尾匹配非空格字符。
#1
12
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.
现在,只有当(?= \ S + $)从这一点开始匹配时,字符串才会被分割为\ s +(空白字符)。并且\ S + $会立即在字符串末尾匹配非空格字符。