This function allows you to take any string and split it into fairly even pieces

Posted on Aug 23, 2011 in PHP
This function allows you to take any string and split it into fairly even pieces

<? 

function breakString($str="", $pieces="") { 

// Find out how big the string is 
$len = strlen($str); 

// String size can't be less than pieces 
if ($len < $pieces) { 
    $ary[0] = "String Size is less than Number of Pieces"; 
    return $ary; 
} 

// Find out how big each piece should be 
$lim = $len / $pieces; 
$start = 0; 
$i = 0; 
$l = 0; 

// Split string into individual characters 
for ($k = 0; $k < $len; $k++) { 
     $x = $k + 1; 
     $g[$k] = substr($str,$k,1); 
} 

// Start Making Pieces 
while ($i < $pieces) { 
    
// Glue Pieces Back Togeather 
   for ($j = $start; $j < $lim; $j++) { 
       $tmp = $tmp . $g[$l]; 
       $l++; 
   } 

// Back up one character in the array 
   $x = $l - 1; 

// If Last Charecter is NOT a space, AND this is NOT the last piece, 
// Go until the next  space is found 
   while (($g[$x] != " ") AND ($i != $pieces -1)) { 
     $tmp = $tmp . $g[$l]; 
     $g[$x] = $g[$l]; 
     $l++; 
   } 

// Move this String into array piece 
   $ary[$i] = $tmp; 
// Reset String 
   $tmp = ""; 
   $i++; 
} 

// Output String 
   return $ary; 

} 

$text = "this is a little test with php3, MYSQL and Apache on my webserver. It works fine but i have to learn a lot about php3!"; 
echo("<b>$text</b><br><br>"); 

$now = breakString($text, 3); 

$sze = sizeof($now); 

for ($ii = 0; $ii < $sze; $ii++) { 
     echo("$now[$ii]<br>"); 
} 

?>