Web Hosting Talk







View Full Version : [PHP] Shortening Text from DB


Danny159
09-09-2009, 04:33 AM
Hey,

I have a database that runs the news for a website, this includes HTML such as <b>, <i>, <u>

However I need to make the text shorter to 255 letters and add ... but take of ending of words.

But I cant get my script to do it!

Here is that I have....



$desc = $row["post_content"];


$desc = trim(substr($desc, 0, 256));
$len = strlen($desc) -1;
$x = strpos($desc, '<');
if($x !== false && $x < $len) $len = $x;
if($desc[$len] != ".")
{
while($len > 20 && ord($desc[$len]) != 32) $len--;
}
$desc = trim(substr($desc, 0, $len)) . "...";


echo "$desc";

Please help asap
Dan

WebNaz
09-09-2009, 09:09 AM
A function like the one below should do the job, but if you dont strip the tags, you might get unexpected results because of improperly closed/open tags.

function short_txt($str,$char){
$str = strip_tags($str);
$str = ereg_replace("[\r\t\n\"]"," ",$str);
$str =substr($str, 0, $char);
$str = substr($str,0,strrpos($str ," "));
return $str."...";
}

$desc = $row["post_content"];
echo short_txt($desc,'255');