Принимая ваш вопрос буквально
Как бы я разделил предложение на две части, пока ни одна из полученных частей не будет длиннее, скажем, 8 слов?
, более конкретно
повторяющееся деление пополам, пока ни один кусок не будет длиннее 8.
на счет:
$sentence = "This is a long string that can be different since this is a black box function and I do not know what strings I am going to receive, but I need to be shorter for sure by a lot.";
$say8words = 8;
# start with one piece, use preg_split for finer control.
$pieces[] = explode(' ', $sentence);
while(is_a_piece_longer_than($pieces, $say8words))
$pieces = splitting_in_half($pieces);
echo as_string($pieces);
Что даст вам:
This is a long string that
can be different since this
is a black box function
and I do not
know what strings I am going
to receive, but I
need to be shorter for
sure by a lot.
и может быть не тем, о чем вы на самом деле думали, что просили.
Функции:
function is_a_piece_longer_than($pieces, $length)
{
return $length < max(array_map('count', $pieces));
}
function splitting_in_half($pieces)
{
$halfs = array();
foreach($pieces as $full)
{
$count = count($full);
$halfCount = 1 + (int) ($count / 2);
foreach(array_chunk($full, $halfCount) as $half)
$halfs[] = $half;
}
return $halfs;
}
function as_string($pieces)
{
return array_reduce($pieces, function($v, $w) { return $v . (strlen($v) ? "\n" : '') . implode(' ', $w);}, '');
}