简体   繁体   English

如何在不中断单词的情况下拆分长字符串?

[英]How to split a long string without breaking words?

I'm looking for something along the line of我正在寻找类似的东西

str_split_whole_word($longString, $x)

Where $longString is a collection of sentences, and $x is the character length for each line.其中$longString是句子的集合, $x是每行的字符长度。 It can be fairly long, and I want to basically split it into multiple lines in the form of an array.它可能相当长,我想基本上以数组的形式将其拆分为多行。

For example:例如:

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

Desired output:期望的输出:

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

The easiest solution is to use wordwrap() , and explode() on the new line, like so:最简单的解决方案是在新行上使用wordwrap()explode() ,如下所示:

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

Where $x is a number of characters to wrap the string on.其中$x是用于包装字符串的字符数。

This code avoid breaking words, you won't get it using wordwrap().这段代码避免了断词,你不会使用 wordwrap() 得到它。

The maximum length is defined using $maxLineLength .最大长度使用$maxLineLength定义。 I've done some tests and it works fine.我已经做了一些测试,它工作正常。

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

Use wordwrap() to insert the linebreaks, then explode() on those linebreaks:使用wordwrap()插入换行符,然后在这些换行符上 expand 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."
}

This whole task can be accomplished with just one preg_ function call.只需调用一个preg_函数即可完成整个任务。

  1. Match any character between zero and $maxLength times.匹配零到$maxLength时间之间的任何字符。
  2. Forget/Release the matched characters from #1 with \\K .使用\\K忘记/释放 #1 中匹配的字符。
  3. Match the next one or more whitespace characters or the end of the string.匹配下一个或多个空白字符或字符串的结尾。 The characters/position matched here will be consumed in the splitting process and will not appear in the output array.这里匹配的字符/位置将在拆分过程中被消耗,不会出现在输出数组中。
  4. Set the preg_ function to exclude the empty element that is produced by splitting on the end of string position with PREG_SPLIT_NO_EMPTY .设置preg_函数以排除通过使用PREG_SPLIT_NO_EMPTY在字符串位置的末尾拆分而产生的空元素。

Code: ( Demo )代码:(演示

$longString = 'I like apple. You like oranges. We like fruit. I like meat, also.';
$maxLength = 18;

var_export(
    preg_split("/.{0,{$maxLength}}\K(?:\s+|$)/", $longString, 0, PREG_SPLIT_NO_EMPTY)
);

Output:输出:

array (
  0 => 'I like apple. You',
  1 => 'like oranges. We',
  2 => 'like fruit. I like',
  3 => 'meat, also.',
)

If your input string might contain newlines, then just add the s pattern modifier.如果您的输入字符串可能包含换行符,则只需添加s模式修饰符。
/.{0,{$maxLength}}\\K(?:\\s+|$)/s ( Demo ) /.{0,{$maxLength}}\\K(?:\\s+|$)/s ( Demo )

Made function from Marcio simao comment 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;
}

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', '$1',$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

My requirements were split text string after every 20 characters without break words.我的要求是每 20 个字符后拆分文本字符串而没有断词。 Use wordwrap() to insert the linebreaks after every 20 characters So here is how I do it.使用wordwrap()在每 20 个字符后插入换行符所以这就是我的做法。 hope this is helpful for others who find it this type of solution.希望这对找到此类解决方案的其他人有所帮助。

$charactersLimit = 20;
$yourTextString = 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit.';
$output = explode("\n", wordwrap($yourTextString, $charactersLimit));

Output like this:输出如下:

Array
(
    [0] => Lorem ipsum dolor
    [1] => sit amet,
    [2] => consectetuer
    [3] => adipiscing elit.
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM