PHP:在不中断单词的情况下拆分长字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11254787/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:06:30  来源:igfitidea点击:

PHP: split a long string without breaking words

phpstring

提问by musicliftsme

I'm looking for something along the line of

我正在寻找类似的东西

str_split_whole_word($longString, x)

where $longStringis a collection of sentences, and xis the character length for each line. It can be fairly long, and I want to basically split it into multiple lines in the form of an array.

其中$longString是句子的集合,x是每行的字符长度。它可能相当长,我想基本上以数组的形式将其拆分为多行。

So for example,

例如,

$longString = 'I like apple. You like oranges. We like fruit. I like meat, also.';
$lines = str_split_whole_word($longString, x);

$lines = Array(
    [0] = 'I like apple. You'
    [1] = 'like oranges. We'
    [2] = and so on...
)

回答by nickb

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

最简单的解决方案是使用wordwrap(), 并explode()在新行上,如下所示:

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

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

哪里$x是用于包装字符串的字符数。

回答by Marcio Mazzucato

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

这段代码避免了断词,你不会使用 wordwrap() 得到它。

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

最大长度使用 定义$maxLineLength。我已经做了一些测试,它工作正常。

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

回答by Michael Berkowski

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

使用wordwrap()插入换行符,然后explode()对这些换行:

// 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."
}

回答by Roman Losev

Made function from Marcio simaocomment

来自Marcio simao评论的功能

function explodeByStringLength($string,$maxLineLength)
{
    if(!empty($string))
    {
        $arrayWords = explode(" ",$string);

        if(count($arrayWords) > 1)
        {
            $maxLineLength;
            $currentLength = 0;

            foreach($arrayWords as $word)
            {
                $wordLength = strlen($word);
                if( ( $currentLength + $wordLength ) <= $maxLineLength )
                {
                    $currentLength += $wordLength;
                    $arrayOutput[] = $word;
                }
                else
                {
                    break;
                }
            }

            return implode(" ",$arrayOutput);
        }
        else
        {
            return $string;
        }       
    }
    else return $string;
}

回答by edCoder

Try This Function.......

试试这个功能......

<?php
/**
 * trims text to a space then adds ellipses if desired
 * @param string $input text to trim
 * @param int $length in characters to trim to
 * @param bool $ellipses if ellipses (...) are to be added
 * @param bool $strip_html if html tags are to be stripped
 * @param bool $strip_style if css style are to be stripped
 * @return string
 */
function trim_text($input, $length, $ellipses = true, $strip_tag = true,$strip_style = true) {
    //strip tags, if desired
    if ($strip_tag) {
        $input = strip_tags($input);
    }

    //strip tags, if desired
    if ($strip_style) {
        $input = preg_replace('/(<[^>]+) style=".*?"/i', '',$input);
    }

    if($length=='full')
    {

        $trimmed_text=$input;

    }
    else
    {
        //no need to trim, already shorter than trim length
        if (strlen($input) <= $length) {
        return $input;
        }

        //find last space within length
        $last_space = strrpos(substr($input, 0, $length), ' ');
        $trimmed_text = substr($input, 0, $last_space);

        //add ellipses (...)
        if ($ellipses) {
        $trimmed_text .= '...';
        }       
    }

    return $trimmed_text;
}
?>

Credit: http://www.ebrueggeman.com/blog/abbreviate-text-without-cutting-words-in-half

信用:http: //www.ebrueggeman.com/blog/abbreviate-text-without-cutting-words-in-half