用php剪切文本块并包装它


Cut block of text with php and wrap it

假设我有一个文本块,可以是1000行或更多,我希望每200行剪切一个块并将其包装在div中?

我可以找到一个解决方案,也许你们可以给我一个片段,如果你们愿意的话。

谢谢。

假设您的行用'n:分隔

 // Split text into separate lines
 $lines = explode("'n",$text);
 // This will hold the resulting string
 $output = '';
 // Loop the array 200 lines at a time
 for ($pos = 0, $linesLeft = count($lines); $linesLeft > 200; $pos += 200, $linesLeft -= 200) {
   $output .= '<div>'.implode("'n",array_slice($lines,$pos,200))."</div>'n";
 }
 // Add the last block, if any
 if ($linesLeft > 0) {
   $output .= '<div>'.implode("'n",array_slice($lines,$pos))."</div>";
 }

EDIT如果处理的是单词而不是行,只需将'n替换为空格即可。或者做:

 $lines = preg_split('/'s+/',$text);