PHP:拆分长字符串而不会破坏单词

时间:2012-06-29 00:44:09

标签: php string

我正在寻找

的内容
str_split_whole_word($longString, x)

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

例如,

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

7 个答案:

答案 0 :(得分:44)

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

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

其中$x是要包装字符串的字符数。

答案 1 :(得分:13)

此解决方案可确保创建行而不会破坏单词,使用wordwrap()将无法获得。 它将使用空间来爆炸字符串,然后使用foreach循环数组并创建行而不会破坏工作并使用$maxLineLength定义的最大长度。下面是代码,我做了一些测试,它工作正常。

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

$arrayWords = explode(' ', $longString);

$maxLineLength = 18;

$currentLength = 0;
$index = 0;

foreach ($arrayWords 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) {
        $arrayOutput[$index] .= $word . ' ';

        $currentLength += $wordLength;
    } else {
        $index += 1;

        $currentLength = $wordLength;

        $arrayOutput[$index] = $word;
    }
}

答案 2 :(得分:10)

使用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."
}

答案 3 :(得分:1)

来自 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;
}

答案 4 :(得分:1)

尝试此功能.......

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

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

答案 5 :(得分:1)

仅需一个preg_函数调用即可完成整个任务。

  1. 匹配零到$maxLength次之间的任何字符。
  2. 使用\K忘记/释放#1中匹配的字符。
  3. 匹配下一个或多个空格字符或字符串的结尾。此处匹配的字符/位置将在拆分过程中使用,并且不会出现在输出数组中。
  4. 设置preg_函数以排除通过用PREG_SPLIT_NO_EMPTY在字符串位置的末尾分割而产生的空元素。

代码:(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)
);

输出:

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

如果输入字符串可能包含换行符,则只需添加s模式修饰符。
/.{0,{$maxLength}}\K(?:\s+|$)/sDemo

答案 6 :(得分:0)

我的要求是每隔20个字符后使用不带断词的拆分文本字符串。使用wordwrap()在每20个字符后插入换行符,这就是我的操作方法。希望这对其他找到这种解决方案的人有所帮助。

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

输出如下:

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