3v4l.org

run code in 300+ PHP versions simultaneously
<?php $longString = 'I like apple. You like oranges. We like fruit. I like meat, also.'; $maxLineLength = 18; $words = explode(' ', $longString); $currentLength = 0; $index = 0; foreach ($words as $word) { // +1 because the word will receive back the space in the end that it loses in explode() $wordLength = strlen($word) + 1; if (($currentLength + $wordLength) <= $maxLineLength) { $output[$index] .= $word . ' '; $currentLength += $wordLength; } else { $index += 1; $currentLength = $wordLength; $output[$index] = $word; } } var_export($output);

preferences:
25.97 ms | 405 KiB | 5 Q