[SOLVED] PHP Parsing Text Into 3 Rows Without Splitting Up Words

Issue

I am trying to figure out how to parse text into 3 lines up to 15 characters per line without splitting up words. The application is to show a summary with a “Continue Reading” link on the web page.

An example of what I am trying to achieve is as follows: If we take the phrase

The lazy dog jumped over the quick brown fox yesterday.

I want each line to have up to 15 characters.

An example of what I want the result to be is:

The lazy dog
jumped over the
quick brown fox
  • I am trying to avoid the situation such as the word “jumped” being split between two lines: “The lazy dog ju” is 15 characters.
  • On line 2 “jumped over the” is exactly 15 characters.
  • Whatever text remains isn’t used.

I’ve adapted the example GentlemanMax provided to output the results in an array:

/**
 * Split Text
 * 
 * @param string $string
 * @param int    $totalRow
 * @param int    $lineLength
 *
 * @return array
 */
function SplitText($string, $totalRow = 3 , $lineLength = 15) {

    $result = [];
    $row = 0;
    $words = explode(' ', $string);
    $result = '';
    $line = '';

    foreach( $words as $word ) {

        if( strlen(trim($line)) + strlen($word) +1 > $lineLength ) {

            $result[$row] = $line . trim($word);
            ++$row;

            if ( $row == $totalRow ) { break; }

        } else {

            $line .= $word . ' ';

        }

        if(!empty($line)) $result[$row] = $line;

    }

    return $result;
}

Solution

The most basic version of this function looks something like this.

function splitText($string, $lineLength = 15){
    $words = explode(' ', $string);
    $result = '';
    $line = '';
    foreach($words as $word){
        if( strlen(trim($line)) + strlen($word) +1 > $lineLength ){ 
            //Change PHP_EOL to your preferred new line delimiter
            $result .= trim($line) . PHP_EOL; //remove the trailing space from line.
            $line = $word . ' ';
        }
        else $line .= $word . ' ';
    }

    if(!empty($line)) $result .= $line;

    return $result;
}

That will split your string into lines. This could be easily modified to limit the number of lines returned or append other characters to the end of the last line. Note, this assumes that words are delimited by spaces and that punctuation counts toward the 15 characters.

This also assumes you want \n (newline) characters as your line delimiter. You can replace PHP_EOL with whatever you want your line break character to be.

Answered By – TheGentleman

Answer Checked By – Marilyn (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *