hopefully this should be a quick and simple one, using PHP I’m trying to split a string into an array but by only the last instance of whitespace. So far I have…
$str="hello this is a space"; $arr=preg_split("/\s+/",$str); print_r($arr); Array (  => hello  => this  => is  => a  => space )
…which splits by all instances of whitespace.
How can I expand this regular expression to split by only the last instance of whitespace? To become…
Array (  => hello this is a  => space )
Thank you in advance of your help!
A short explanation:
(?= ... ) is called a positive look ahead. For example,
a(?=b) will only match a single
'a' if the next character (the one to the right of it) is a
'b'. Note that the
'b' is not a part of the match!
$ denotes the end of the string.
To recap, the complete regex
\s+(?=\S*+$) would read in plain English as follows:
match one or more white space characters only when looking ahead of those white space characters zero or more characters other than white space characters, followed by the end of the string, can be seen.
Answered By – Bart Kiers
Answer Checked By – Dawn Plyler (BugsFixing Volunteer)