22

我正在寻找类似的东西

str_split_whole_word($longString, $x)

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

5 回答 5

59

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

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

$x包裹字符串的字符数在哪里。

于 2012-06-29T00:46:24.623 回答
19

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

The maximum length is defined using $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;
    }
}
于 2012-06-29T04:39:09.573 回答
13

用于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."
}
于 2012-06-29T00:46:49.850 回答
2

我的要求是在每 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.
)
于 2020-09-30T07:54:38.003 回答
2

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

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

代码:(演示

$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+|$)/s演示

于 2020-09-25T07:00:22.690 回答