不使用单词换行的str_split

7
我希望您能为我提供最快的解决方案,将字符串分割成部分,而不进行单词换行。
$strText = "The quick brown fox jumps over the lazy dog";

$arrSplit = str_split($strText, 12);

// result: array("The quick br","own fox jump","s over the l","azy dog");
// better: array("The quick","brown fox","jumps over the","lazy dog");
1个回答

23

你实际上可以使用wordwrap()函数,并将其输入到explode()函数中,使用换行符\n作为分隔符。 explode()函数将在由wordwrap()产生的换行符上拆分字符串。

$strText = "The quick brown fox jumps over the lazy dog";

// Wrap lines limited to 12 characters and break
// them into an array
$lines = explode("\n", wordwrap($strText, 12, "\n"));

var_dump($lines);
array(4) {
  [0]=>
  string(9) "The quick"
  [1]=>
  string(9) "brown fox"
  [2]=>
  string(10) "jumps over"
  [3]=>
  string(12) "the lazy dog"
}

3
注意:使用 false(默认值)作为第四个参数可以防止在换行时断开单词。这正是我所需要的。如果您不关心是否断开单词,请将其设置为 true。 - Ryan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接