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

mus*_*sme 18 php string

我正在寻找一些东西

str_split_whole_word($longString, x)
Run Code Online (Sandbox Code Playgroud)

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...
)
Run Code Online (Sandbox Code Playgroud)

nic*_*ckb 48

最简单的解决方案是使用wordwrap(),并explode()在新的生产线,就像这样:

$array = explode( "\n", wordwrap( $str, $x));
Run Code Online (Sandbox Code Playgroud)

$x包含字符串的字符数在哪里.

  • 这是如此简单和令人难忘; 应该是接受的答案! (11认同)
  • 如果您在字符串中没有换行符,这将很有用. (2认同)

Mar*_*ato 17

这个解决方案可以确保创建行而不会破坏单词,使用wordwrap()将无法获得.它将使用空间来爆炸字符串,然后使用foreach循环数组并创建行而不会破坏工作并使用最大长度$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;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 马西奥,谢谢你的帮助.这就像你描述的那样有帮助! (2认同)

Mic*_*ski 11

使用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."
}
Run Code Online (Sandbox Code Playgroud)