$str="really long str with more than thirty three chars";
$max=33;
$modstr=((strlen($str)>$max)?substr($str,0,$max) . "..." : $str);
echo $modstr;
i made it modstr so $str retains its value, incase you need it for anything
to retain full words, this worked pretty good
// it seems like the script is needed for important things =)
$str="Two members of the senate were found smoking crack yesterday morning";
$max=33;
$words=explode(" ",$str);
for($i=0;$i<count($words);$i++)
{
static $char_count=0, $outstr="";
$char_count+=strlen($words[$i]);
if($char_count<=$max)
$outstr.=$words[$i] . " ";
else{
$outstr.="...";
continue 1;
}
}
echo $outstr;
play with those i guess 😃
since im bored and have nothing else to do: heres that in function form
function shorten($str,$max=33,$buffer="...")
{
$words=explode(" ",$str);
for($i=0;$i<count($words);$i++)
{
static $char_count=0, $outstr="";
$char_count+=strlen($words[$i]);
if($char_count<=$max)
$outstr.=$words[$i] . " ";
else{
$outstr.=$buffer;
continue 1;
}
}
return $outstr;
}
// example
echo shorten($str,33,".,.");