Search code examples
phptextsplitcpu-wordimbalanced-data

Split text into an array of N elements with a balanced number of words in each element


I wanted to split a large text into 10 pieces (somehow equal parts). Ii use this function:

function chunk($msg) {
    $msg = preg_replace('/[\r\n]+/', ' ', $msg);
    //define character length of each text piece
    $chunks = wordwrap($msg, 10000, '\n');
    return explode('\n', $chunks);
}

$arrayys = chunk($t);
foreach ($arrayys as $partt) {
    echo $partt . "<br/><br/><br/>";
}

But is it possible to define word length of each text piece (not character length )? how to divide text into words in such situation?


Solution

  • I would suggest to use "explode" http://php.net/manual/en/function.explode.php for splitting the string by spaces. Then you'll get an array of words on which you can iterate and build your text-parts.