Alex Rivera | Logout

Regex to split a string only by the last whitespace character

Asked 2009-10-07T10:53:57.583
15

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 ( [0] => hello [1] => this [2] => is [3] => a [4] => 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 ( [0] => hello this is     a [1] => space ) 

Thank you in advance of your help!

Edit
Report

1 Answer

0

If the * and + after \S dupicated? Only /\s+(?=\S+$)/ or /\s+(?=\S*$)/ is enough depends on the need.

answered 2009-10-08T22:17:21.970

Your Answer