2012-03-10 61 views
6

我在寻找最快解决方案,以将字符串转换为零件,而不是str_split不带自动换行

$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"); 

回答

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" 
} 
+0

+1非常狡猾。 – 2012-03-10 17:28:33

+3

注意:使用false(默认)作为第四个参数可防止包装时单词被破坏。正是我需要的。如果你不关心破坏单词,请将其设置为true。 – rncrtr 2013-04-12 22:54:52