$str = \"This is a string\";
$words = explode(\" \", $str);
Works fine, but spaces still go into array:
$words === array (\'This
Here is one way, splitting the string and running a regex once, then parsing the results to see which segments were captured as the split (and therefore only whitespace), or which ones are words:
$temp = preg_split('/(\s+)/', $str, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
$spaces = array();
$words = array_reduce( $temp, function( &$result, $item) use ( &$spaces) {
if( strlen( trim( $item)) === 0) {
$spaces[] = strlen( $item);
} else {
$result[] = $item;
}
return $result;
}, array());
You can see from this demo that $words
is:
Array
(
[0] => This
[1] => is
[2] => a
[3] => string
)
And $spaces
is:
Array
(
[0] => 1
[1] => 1
[2] => 4
)