There can be many unexpected situations i tried to cover as many as i can them up:
<?
$string_1 = "anavaragelongword shortword";
$string_2 = "averylongwordwhichisprobablymorethan30characters word1";
$string_3 = "word2 word3 averylongwordwhichisprobablymorethan30characters";
$string_4 = "three avarege words";
$char_length = 30;
echo slidedescription($string_1, $char_length);
echo slidedescription($string_2, $char_length);
echo slidedescription($string_3, $char_length);
echo slidedescription($string_4, $char_length);
function slidedescription($string, $char_length)
{
$total_length = null;
$slidedescription = null;
$length = strlen($string);
if($length>$char_length) {
$array = explode(" ", $string);
foreach ($array as $key => $value) {
$value_length[$key] = strlen($value);
$total_length = $total_length + $value_length[$key];
if ($total_length<=$char_length) {
$slidedescription .= $value." ";
}
if (!$slidedescription) {
$slidedescription = substr($value,0,$char_length).'...';
}
}
} else {
$slidedescription = $string;
}
$last = trim($slidedescription).'... <br />';
return $last;
}