<?php
// This function will try to split the string at word boundaries as much as possible.
// If the string is longer than $len, it will be split into a max of $len characters per part.
// returns an array of strings
function split_str($str, $len)
{
$temp = array();
$max = strlen($str);
$len = $len ? abs($len) : $max;
if ($len >= $max)
{
$temp[] = $str;
return $temp;
}
$start = 0;
$end = $len;
do // what makes things tricky is because strings like arrays start at 0
{
while (($end > $start) && !is_punct($str{$end}))
{
$end--;
}
if ($end > $start)
{
$end = (($end - $start) < $len) ? $end + 1 : $end;
$temp[] = substr($str, $start, ($end - $start));
}
else
{
$end += $len;
$temp[] = substr($str, $start, $len);
}
$start = $end;
$end += $len;
}
while ($start < $max);
return $temp;
}
// some helper function, returns true if $c is a punctuation, otherwise, false
function is_punct($c)
{
// change this regex to your liking:
return preg_match('/^[`~@#%^&*()\-=_+[\]\\{}|;\':",.\/\<\>?\s]$/', $c);
}
// call it like: (just for testing)
$s = 'The quick brown fox jumps over the lazy dog. The lazy dog, jumps over the quick brown fox.';
$t = split_str($s, 10);
// then access each like
$i = 0;
foreach ($t as $v)
{
echo $i++ . ' |' . $v . '|<br />'; // I used | just to see the spaces
}
//var_dump($t);