<?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);
Warning: Undefined variable $output in /in/Ref5f on line 16
Warning: Undefined array key 0 in /in/Ref5f on line 16
array (
0 => 'I like apple. You ',
1 => 'likeoranges. We ',
2 => 'likefruit. I ',
3 => 'likemeat, also. ',
)
Notice: Undefined variable: output in /in/Ref5f on line 16
Notice: Undefined offset: 0 in /in/Ref5f on line 16
array (
0 => 'I like apple. You ',
1 => 'likeoranges. We ',
2 => 'likefruit. I ',
3 => 'likemeat, also. ',
)