musicliftsme musicliftsme - 17 days ago 5
PHP Question

PHP: split a long string without breaking words

I'm looking for something along the line of

str_split_whole_word($longString, x)


where
$longString
is a collection of sentences, and
x
is the character length for each line. It can be fairly long, and I want to basically split it into multiple lines in the form of an array.

So for example,

$longString = 'I like apple. You like oranges. We like fruit. I like meat, also.';
$lines = str_split_whole_word($longString, x);

$lines = Array(
[0] = 'I like apple. You'
[1] = 'like oranges. We'
[2] = and so on...
)

Answer

This solution ensures that the lines will be created without breaking words, what you won't get using wordwrap(). It will use the space to explode the string and then use a foreach to loop the array and create the lines without breaking works and with a maximum length that is defined using $maxLineLength. Below is the code, i've done some tests and it works fine.

$longString = 'I like apple. You like oranges. We like fruit. I like meat, also.';

$arrayWords = explode(' ', $longString);

// Max size of each line
$maxLineLength = 18;

// Auxiliar counters, foreach will use them
$currentLength = 0;
$index = 0;

foreach ($arrayWords 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) {
        $arrayOutput[$index] .= $word . ' ';

        $currentLength += $wordLength;
    } else {
        $index += 1;

        $currentLength = $wordLength;

        $arrayOutput[$index] = $word;
    }
}