没有自动换行的str_split

时间:2012-03-10 16:24:07

标签: php string split word-wrap

我正在寻找最快的解决方案,将字符串分成几部分,而不是

$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 个答案:

答案 0 :(得分:21)

您实际上可以使用wordwrap(),使用换行符explode()作为分隔符加入\nexplode()会将字符串拆分为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"
}