How to split a long string without breaking words?

This code avoid breaking words, you won't get it using wordwrap().

The maximum length is defined using $maxLineLength. I've done some tests and it works fine.

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

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

$maxLineLength = 18;

$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;
    }
}

Use wordwrap() to insert the linebreaks, then explode() on those linebreaks:

// Wrap at 15 characters
$x = 15;
$longString = 'I like apple. You like oranges. We like fruit. I like meat, also.';
$lines = explode("\n", wordwrap($longString, $x));

var_dump($lines);
array(6) {
  [0]=>
  string(13) "I like apple."
  [1]=>
  string(8) "You like"
  [2]=>
  string(11) "oranges. We"
  [3]=>
  string(13) "like fruit. I"
  [4]=>
  string(10) "like meat,"
  [5]=>
  string(5) "also."
}

The easiest solution is to use wordwrap(), and explode() on the new line, like so:

$array = explode( "\n", wordwrap( $str, $x));

Where $x is a number of characters to wrap the string on.


My requirements were split text string after every 20 characters without break words. Use wordwrap() to insert the linebreaks after every 20 characters So here is how I do it. hope this is helpful for others who find it this type of solution.

$charactersLimit = 20;
$yourTextString = 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit.';
$output = explode("\n", wordwrap($yourTextString, $charactersLimit));

Output like this:

Array
(
    [0] => Lorem ipsum dolor
    [1] => sit amet,
    [2] => consectetuer
    [3] => adipiscing elit.
)