开发者

php: split a string in half at white space until none of the resulting parts are longer than x number of words

How would I split a sentence into half, until none of the resulting parts are longer than, say 8 words?

Here is a sample text of 39 words:

"This is a long string that can be different since this is a black box funct开发者_运维问答ion and I do not know what strings I am going to receive, but I need to be shorter for sure by a lot."

Resulting output

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

Any tips please?


I'd go with wordwrap(). Your example lines are about 35 characters long. Here's one that goes to 40.

echo wordwrap($long_string, 40);

Prints:

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.

Specify the 3rd parameter to wordwrap() if your linebreaks are \r\n rather than the default \n.


Try this

<?php
$text = "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.";
$newtext = wordwrap($text, 40, "\n", true); // assign number as per you requirement

echo "$newtext\n";
?>


Taking your question literally

How would I split a sentence into half, until none of the resulting parts are longer than, say 8 words?

, more specifically

repetitively splitting in half, until no piece is longer than 8.

into account:

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

Which will give you:

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.

and might not be what you actually thought you were asking for.

Functions:

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);}, '');
}


Use str_split(). Check the documentation on php.net

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜