3v4l.org

run code in 300+ PHP versions simultaneously
<?php $string = "This is a string"; $words = []; $spaces = []; foreach (preg_split('~( +)~', $string, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE) as $s) { if (ctype_space($s)) { $spaces[] = strlen($s); } else { $words[] = $s; } } var_export([ 'words' => $words, 'spaces' => $spaces ]);

preferences:
45.71 ms | 402 KiB | 5 Q