没有自动换行的str_split

mat*_*e64 6 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");
Run Code Online (Sandbox Code Playgroud)

Mic*_*ski 21

实际上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"
}
Run Code Online (Sandbox Code Playgroud)

  • 注意:使用false(默认值)作为第4个参数可以防止在换行时单词被破坏.正是我需要的.如果您不在乎破坏单词,请将其设置为true. (3认同)